T
TanStack2y ago
constant-blue

How to trigger query when url param changes

export const useNotes = () => {
const queryParams = new URLSearchParams();

const fetchNotes = async () => {
const from = queryParams.get("from");

if (from) {
queryParams.append("from", from);
} else {
queryParams.delete("from");
}

const result = await axios.get(`/api/notes${encodeURIComponent(queryParams.toString())}`);
return result.data;
};

const { data, error, isLoading, refetch } = useQuery<Array<INote>, Error>({ queryKey: ['notes', queryParams], queryFn: fetchNotes });

return { notes: data, error, isLoading, refetch };
};
export const useNotes = () => {
const queryParams = new URLSearchParams();

const fetchNotes = async () => {
const from = queryParams.get("from");

if (from) {
queryParams.append("from", from);
} else {
queryParams.delete("from");
}

const result = await axios.get(`/api/notes${encodeURIComponent(queryParams.toString())}`);
return result.data;
};

const { data, error, isLoading, refetch } = useQuery<Array<INote>, Error>({ queryKey: ['notes', queryParams], queryFn: fetchNotes });

return { notes: data, error, isLoading, refetch };
};
I have a toggle that either adds or remove the "from" parameter in the url. It does this in the URL, but the fetchNotes function isn't re-run?
1 Reply
sunny-green
sunny-green2y ago
make sure that everything you put into the query key is serializable

Did you find this page helpful?