CDLUC3 / dmsp_frontend_prototype

Repo to test out new NextJS framework
MIT License
0 stars 0 forks source link

Frontend Infrastructure - File structure and shared methods for GraphQL requests #28

Closed jupiter007 closed 3 months ago

jupiter007 commented 5 months ago

For the DMPTool Rebuild frontend development, we are planning to use the latest version of NextJS 14 with App Router(i.e., React Server Components (RSC).

There are some nuances with the caching when using Apollo Client with RSC Server components in this version. Server Components must be manually refreshed when data changes. So if the same data is used in Client Components and Server Components, both environments might get out of sync. Apollo created experimental library that allows us to use Apollo Client in these RSC components: @apollo/experimental-nextjs-app-support. You can read more about it in these Apollo GraphQL blogs:

Apollo suggests that developers should choose whether to render Apollo Client data objects in RSC or in Client Components. When data is fetched from a GraphQL server, it is normalized into entities and stored in the cache. Subsequent queries can then retrieve data from the cache using the same entity structure, rather than refetching the data from the server. Therefore, when deciding whether to render each entity in RSC or in Client Components, it is important to consider how the data will be accessed and updated in the cache.

We need to install both @apollo/client and @apollo/experimental-nextjs-app-support and then choose between using Server Components or Client Components to make our GraphQL requests.

If we use GraphQL requests in Client Components, we can create one, shared client instance, lib/apollo-client.ts, and reference that client in our components to call on query or mutation functions saved at lib/graphql/client/. That should work the same as it always has. If we need to use Apollo hooks in our Client Components, we might have to use the ApolloWrapper that is suggested in the above blog.

If we choose to make GraphQL requests in our Server Components, we can follow the instructions outlined in the above blogs, and create a lib/client.js file and use getClient() to make the requests. In order to refresh data on the server side, we have to use revalidate in our fetchOptions.