so I have this code
const [localState, setLocalState] = useState<StateType[]>([]);
const { data = { attribute: [] }, loading } = useQuery<DataType>(QUERY, {
variables: {
id: client && client.id
},
skip: user.clients && user.clients.length === 0
});
useEffect(() => {
if (loading || !data) {
return undefined;
}
if (data && data.attribute) {
const sortedResult = data.attribute.sort((a, b) =>
a.updatedAt < b.updatedAt ? 1 : -1
);
setLocalState(sortedResult);
}
}, [data]);
the issue is when useQuery returns empty(undefined) result and data defaults to {attribute: []} useEffect keeps being triggered for forever, however when useQuery returns data (so it is not defaulted) useEffects is being entered only once. The solution for this problem was only to remove default parameter = {attribute: []} in the query so it looks like this:
const [localState, setLocalState] = useState<StateType[]>([]);
const { data, loading } = useQuery<DataType>(QUERY, {
variables: {
id: client && client.id
},
skip: user.clients && user.clients.length === 0
});
useEffect(() => {
if (loading || !data) {
return undefined;
}
if (data && data.attribute) {
const sortedResult = data.attribute.sort((a, b) =>
a.updatedAt < b.updatedAt ? 1 : -1
);
setLocalState(sortedResult);
}
}, [data]);
Why defaulting parameter in useQuery makes useEffect being triggered for infinity?
(Important note to add - I tried to remove sort function, thinking that it mutates data object and causes reentering but it didn't change anything)