I am trying to use useQuery to fetch data when a change is made to a state, a list of strings called validIds. The code is for a csv uploader which receives a list of ids and formats them into a list called formattedIds. Once this list is set in state, I want to trigger the useQuery which will send these ids and return the ids which are valid. If the request is successful I will save the returned ids in state now and create an invalid id list and return them to the user.
However, I have an issue getting into the if(isSuccess) statement in order to create these lists. Relevant code below:
const [validIds, setValidIds] = useState<string[]>([]);
const { data: people, isSuccess } = useQuery({
queryKey: ["People", validIds],
queryFn: () => getPeople(validIds),
enabled: validIds.length > 0,
});
const addFormattedIds = (ids: string[]) => {
setValidIds([]);
const invalidIds: string[] = [];
//Prior validation in order to get formattedIds, a list of strings
setValidIds(formattedIds);
if (isSuccess) {
const returnedIds = people?.data.map((person) => person.id);
const differences = formattedIds.filter((id) => !returnedIds.includes(id));
invalidIds.concat(differences);
setValidIds(returnedIds);
}
if (validIds.length < ids.length) {
console.log(invalidIds);
}
setIdsEnteredAsCsv(validIds);
};
When I call setValidIds(formattedIds), I see the request has been processed in the Network tab of the inspect window. However, the isSuccess statement does not pass so I cannot do anything with the returned data. In the same session, if I upload another csv of ids, it then goes into the if statement, but with the ids that I uploaded previosuly to this. How can I solve this, thanks. Please ask questions if necessary as perhaps I'm not using useQuery in the correct way.
people?.data?.something, imagine that useQuery behave like useState, but on another machine... if it changes, it will rerender with diferent state