Flip
Flip

Reputation: 6781

How to access the props provided by getServerSideProps in the page?

I have a question regarding Next.js with GraphQL/Apollo and Typescript. A Next.js page I am trying to understand exports a getServerSideProps function. How can I access the props or rather the data that I fetch in getServerSideProps in the page? I can see it when I log the props (see code), but it is in the object in a rather unusual format, with the id in the key. My IDE doesn't allow me to get to them via autocomplete; it only "sees" the normal prop graphQlClientId.

Bonus question: I am also unsure what the ctx which is passed into the getServerSideProps is and where it is coming from.

export interface PageProps {
  graphQlClientId: string;
}

export default function Page(props: PageProps) {
  const { graphQlClientId } = props;
  console.log(props);
  // {
  //   ...
  //   graphQlClientId: "12dpZ450LTsadsf",
  //   __APOLLO_STATE__: {
  //     ROOT_QUERY: {
  //       user({"id":"12dpZ450LTsadsf"}): {
  //         name: 'Carl C'
  //       }
  //     }
  //   }
  // }

  return (
    <Layout graphQlClientId={graphQlClientId}>
      <SomeComponent user={user} />
    </Layout>
  );
}

export const getServerSideProps: GetServerSideProps = async (ctx) => {
  const { apolloClient, clientId, authToken, csrfToken } = await getApolloClient(ctx);

  const userDataRequest = apolloClient.query({
    query: GetUserDocument,
    variables: { clientId: clientId },
  });

  await userDataRequest.catch((err) => {
    console.error(err);
  });

  return withApolloState({ apolloClient, authToken, clientId, csrfToken });
};

Upvotes: 1

Views: 754

Answers (1)

jordiburgos
jordiburgos

Reputation: 6302

First the easy question, ctx is the context parameter for the getServerSideProps function. It contains the request object, the response object, route parameters, query parameters, and so on...

You use the context to create the initial data for the page i.e. you get a query parameter 'id' and query the database for that ID. Then you have that data available in pageProps.

See this page https://nextjs.org/docs/api-reference/data-fetching/get-server-side-props for more detailed info.

The main question. When you return return withApolloState({ apolloClient, authToken, clientId, csrfToken }); you are sending this object { apolloClient, authToken, clientId, csrfToken } to the pageProps.

Here you are not setting a type, so you can't "see" what is there with your IDE. Also, is that the data that you want to use in your page?

To fix it, define a type and return an object of that type:

type T {
    clientId string
    authToken string
    ...
}


export const getServerSideProps: GetServerSideProps = async (ctx) : T => {
    ...
    return { ... } as T;
}

Upvotes: 1

Related Questions