|
I am struggling with fetching the data when query params change. There may be a lot of different search params in the url, so React.useEffect(
() => subscribeToQueryUpdates(({ searchParams }) => {},
[]
)The structure I have is: const ServerComponent = ({searchParams}) => {
const initialData = await fetchInitialData({searchParams});
return <ItemsList initialData={initialData} />
}
// ItemsList
'use client'
export const ItemsList = ({ initialData }) => {
const prevSearchParamsRef = useRef(searchParams);
const [items, setItems] = useState(initialData);
const [searchParams] = useQueryStates({
...
});
useEffect(() => {
const fetch = async (searchParams) => {
try {
const { data } = await apiService().get('/items', searchParams);
setItems(data);
} catch (error) {}
};
if (!isEqual(prevSearchParamsRef.current, searchParams)) {
prevSearchParamsRef.current = searchParams;
fetch({ ...searchParams, page: 0 });
}
}, [searchParams]);
}As soon as I do
I double checked and there is no logic which would do that. React.useEffect(
() => subscribeToQueryUpdates(({ searchParams }) => {},
[]
)But that caused an infinite loop... Am I doing something wrong or is it not possible to it at all? |
Replies: 2 comments 1 reply
|
Sorry for the noise - looks like there is some additional logic in the code which causes this issue. |
|
I wouldn't recommend depending on
What version of Next.js and One last tip: you can await the setState to know when the URL is up to date, and trigger your client-side fetch there, if it makes sense. The awaited result is a |
I wouldn't recommend depending on
subscribeToQueryUpdates, it's marked as deprecated and will be removed in v2 which will be released early February.What version of Next.js and
nuqsare you using ? Please refer to the compatibility table, there have been known cases where nuqs' shallow updates would be reset by the Next.js router.One last tip: you can await the setState to know when the URL is up to date, and trigger your client-side fetch there, if it makes sense. The awaited result is a
URLSearchParamsobject of thelocation.searchthat was applied.