T
TanStack3y ago
rare-sapphire

React Query + NextJS Query Params

I have a React Query inside a React Hook which I am accessing from a NextJS route. Example: /about When I access the route directly, the query works as expected and I can see the query in the react query dev tools. However, I am using NextJS URL query params to control some state. When I access the page with the query params, the react query doesn't work as expected - I cannot invalidate the state and the state doesn't even show in the react query dev tools. Example: /about?isquery=true
6 Replies
rare-sapphire
rare-sapphireOP3y ago
Hopefully I described this properly 🤷🏻‍♂️ It seems that it is being treated as a separate page, however the same components are loaded. Only React Query data is missing
correct-apricot
correct-apricot3y ago
Would you be able to share some code to provide more context?
rare-sapphire
rare-sapphireOP3y ago
import React from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';

const useDataRetrieval = () => {
const { data, isSuccess, refetch } = useQuery(['example'], () => [{ data: 'data' }]);
return { data, isSuccess, refetch };
};

function Example() {
const { data, isSuccess } = useDataRetrieval();
const client = useQueryClient();
if (data && isSuccess) {
return (
<div>
{data.map((item) => (
<div>{item.data}</div>
))}
<button type="button" onClick={() => client.invalidateQueries(['example'])}>
Invalidate
</button>
</div>
);
}
return null;
}

export default Example;
import React from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';

const useDataRetrieval = () => {
const { data, isSuccess, refetch } = useQuery(['example'], () => [{ data: 'data' }]);
return { data, isSuccess, refetch };
};

function Example() {
const { data, isSuccess } = useDataRetrieval();
const client = useQueryClient();
if (data && isSuccess) {
return (
<div>
{data.map((item) => (
<div>{item.data}</div>
))}
<button type="button" onClick={() => client.invalidateQueries(['example'])}>
Invalidate
</button>
</div>
);
}
return null;
}

export default Example;
Save this in pages as example.tsx - Go to http://localhost:3000/example with devtools open & you'll see example key + data. Go to http://localhost:3000/example?withquery=true and it's not there
correct-apricot
correct-apricot3y ago
rare-sapphire
rare-sapphireOP3y ago
You're right, it does work there. That's strange.
correct-apricot
correct-apricot3y ago
I would look for differences in your setup vs the link I shared

Did you find this page helpful?