skip to Main Content

I originally used the code below to set my components state, but I have seen online that

  1. It’s a bad method to set a component’s state as it can introduce bugs
  2. 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


  1. 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

    const [state, setState] = useState(null);
     
    const { data, error, isPending } = useQuery({
      queryKey: ['deviceGetStateAPI', deviceid],
      queryFn: () => deviceGetStateAPI(deviceid),
      onSuccess: data => {
        if (!displaySettings) {
          setDisplaySettings(data)
        }
      },
    });
    
    useEffect(() => {
      setState(data); // or setDisplaySettings(data) ¯_(ツ)_/¯
    }, [data]);
    
    Login or Signup to reply.
  2. Let’s separate the query from your React Component.

    // useDevice.js
    const useDevice = ({deviceId}) => {
        const { data, error, ...queryResponse } = useQuery({
            queryKey: ['deviceGetStateAPI', deviceId],
            queryFn: () => deviceGetStateAPI(deviceId)
        })
    
        return { deviceInfo: data, error } // queryResponse.isLoading, queryResponse.isFetching.
    }
    

    Now your React Component

    const DeviceDetail = () => {
    const { deviceInfo, error } = useDevice({deviceId: 12314})
    
    if (error) { 
        // handle error properly
    }
    
    return <DeviceDetails deviceInfo={deviceInfo} />
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search