Issue
I am facing a problem when dehydrating data to SSR in custom HOC, Specifically, I want to hydrate two keys test1
and test2
from server to client to support SSR but I'm getting undefined value returned from test1
. I think the reason is because the dehydratedState was overwrited. How do I fix this problem?
My code here:
const withHOC = (gssp) => async (context) => {
const queryClient = new QueryClient();
await queryClient.prefetchQuery('test1', () => 'abc123');
const childProps = await gssp(context);
return {
props: {
dehydratedState: dehydrate(queryClient),
...(childProps.props ? childProps.props : {}),
},
};
};
export const getServerSideProps = withHOC(async context => {
const queryClient = new QueryClient();
await queryClient.prefetchQuery('test2', () => 'profile-example-data');
return {
props: {
dehydratedState: dehydrate(queryClient),
},
};
});
// when trying test to get data in component:
queryClient.getQueryData('test1'); // undefined
queryClient.getQueryData('test2'); // profile-example-data
Solution
The props have the same name dehydratedState
, so they overwrite each other. This is not a problem of react-query, but of the getServerSideProps composition.
My best guess on why you wanted to split it into two functions is because there are some pages where you only need 'test1'
, and other pages where you'd want to "enhance" that to prefetch 'test1'
and 'test2'
.
If that's the case, I would either just duplicate the logic or extract just the prefetching part, but not the whole "getServerSideProps" part, to a reusable function. It should also use the same queryClient
because that's where the data goes that you'd want to dehydrate just once:
export const prefetchTest1 = (queryClient) => queryClient.prefetchQuery('test1', () => 'abc123');
export const getServerSideProps = async context => {
const queryClient = new QueryClient();
await prefetchTest1(queryClient)
await queryClient.prefetchQuery('test2', () => 'profile-example-data');
return {
props: {
dehydratedState: dehydrate(queryClient),
},
};
};
Answered By - TkDodo
Answer Checked By - - Terry (ReactFix Volunteer)