Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useQuery after server-side rendering

I'm using next.js and apollo with react hooks.

For one page, I am server-side rendering the first X "posts" like so:

// pages/topic.js

const Page = ({ posts }) => <TopicPage posts={posts} />;

Page.getInitialProps = async (context) => {
    const { apolloClient } = context;
    const posts = await apolloClient.query(whatever);

    return { posts };
};

export default Page;

And then in the component I want to use the useQuery hook:

// components/TopicPage.js

import { useQuery } from '@apollo/react-hooks';

export default ({ posts }) => {
    const { loading, error, data, fetchMore } = useQuery(whatever);

    // go on to render posts and/or data, and i have a button that does fetchMore
};

Note that the useQuery here executes essentially the same query as the one I did server-side to get posts for the topic.

The problem here is that in the component, I already have the first batch of posts passed in from the server, so I don't actually want to fetch that first batch of posts again, but I do still want to support the functionality of a user clicking a button to load more posts.

I considered the option of calling useQuery here so that it starts at the second "page" of posts with its query, but I don't actually want that. I want the topic page to be fully loaded with the posts that I want (i.e. the posts that come from the server) as soon as the page loads.

Is it possible to make useQuery work in this situation? Or do I need to eschew it for some custom logic around manual query calls to the apollo client (from useApolloClient)?

like image 447
Infamous911 Avatar asked Oct 27 '22 09:10

Infamous911


1 Answers

Turns out this was just a misunderstanding on my part of how server side rendering with nextjs works. It does a full render of the React tree before sending the resulting html to the client. Thus, there is no need to do the "first" useQuery call in getInitialProps or anything of the sort. It can just be used in the component alone and everything will work fine as long as getDataFromTree is being utilized properly in the server side configuration.

like image 58
Infamous911 Avatar answered Nov 15 '22 12:11

Infamous911