I originally used the code below to set my components state, but I have seen online that
- It’s a bad method to set a component’s state as it can introduce bugs
- The callbacks on useQuery will be deprecated
So my question is what is the best method to set a state from the data resulting from a useQuery?
const [state, setState] = useState(null);
const stateQuery = useQuery({
queryKey: ['deviceGetStateAPI', deviceid],
queryFn: () => deviceGetStateAPI(deviceid),
onSuccess: data => {
if (!displaySettings) {
setDisplaySettings(data)
}
},
});
2
Answers
You can find a state-mirroring example in the v5 migration docs.
The general idea is to use an effect hook to monitor and synchronise query data state with local state
Let’s separate the query from your React Component.
Now your React Component
Ideally, this is the best way to do it, you don’t need a separate state piece to hold the response of useQuery.
useQuery.data is in reality React.useState hook.