3

So I have getStaticProps and need to do some data fetching based on a variable here is an example

export async function getStaticProps() {
  const res = await fetch(localWordpressUrl, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      query: `
        query AllPostsQuery {
          posts(where: {categoryName: "blog"}) {
            nodes {
              slug
              content
              title
            }
          }
        }
      `,
    })
  });

  const json = await res.json();
  return {
    props: {
      posts: json.data.posts,
    }
  };
}

Where categoryName: "blog" needs to be a variable instead of hard coded. I know you can get the slug, but what I need is before the slug. i.e. site.com/blog/slug. Any suggestions on this?

Tyler Daniel
  • 121
  • 4
  • where does the variable come from? – evolutionxbox May 03 '22 at 15:28
  • either the url or if possible I could pass it in, but im following the [slug].js convention so the issue is that component is getting "called" from – Tyler Daniel May 03 '22 at 15:31
  • Using getStaticProps you can only get the `params,defaultLocale,locale,locales` and not the whole url – Inder May 03 '22 at 15:38
  • is it possible to pass in some variable here from a parent? getStaticProps(context, "someVar") – Tyler Daniel May 03 '22 at 15:40
  • No I don't think you can pass any second parameter. There is nothing mentioned in the docs regarding this – Inder May 03 '22 at 15:45
  • Any suggestion on a fix to my problem. Basically I have a /blog and a /photos. both are using the Link component to render [slug].js {post.title}. In theory I would like to display other posts inside of [slug].js that are in the same category. Currently I have no way of knowing the category. – Tyler Daniel May 03 '22 at 15:47
  • `display other posts inside of [slug].js that are in the same category` I didn't understand this part. Could you elaborate? – Inder May 03 '22 at 15:49

1 Answers1

-2

You're actually really close. What you need is to grab the context out of your getStaticProps function. Add this to your getStaticProps function, and look at the console log to see what's happening.

export async function getStaticProps(context) {
  console.log(JSON.stringify(context, null, 3));

  const { asPath, req, res, pathname, query } = context;
  if (req) {
    let localWordpressURL = req.headers.host;
    console.log(localWordpressURL);
  }
}
P Savva
  • 309
  • 1
  • 5