Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use useQuery hook from ReactQuery to update state?

import React, {useState, useEffect, Component} from 'react';
import {Grid, Paper, TextField} from '@material-ui/core'
import DataManager from './../data_manager/data_manager'

const dataManager = new DataManager();

const Tile = (props)=>{
    // Initializing State Variables
    const [state, setState] = useState({
        data : {}
    })

    const { status, data, error, isFetching } = useQuery("data",async()=>{
        const res = await fetch("localhost:8000");
        return res.json()
    }

    if(status==="success"){
        setState({data})
    }else{
        return(<p>Doing</p>)
    }
}

This code results in an infinite loop where the rendering keeps going on in a loop.

I think it is because setState causes useQuery to execute again setting the state again and so on.

Any help is appreciated. I want to store the data I get from useQuery in a state variable.

TIA.

like image 253
asds_asds Avatar asked May 13 '26 13:05

asds_asds


1 Answers

You might want to use useEffect as for now you fetch on every render:

const Tile = (props) => {
  const [state, setState] = useState({
    data: {},
  });

  const { status, data, error, isFetching } = useQuery("data", async () => {
    const res = await fetch("localhost:8000");
    return res.json();
  });

  useEffect(() => {
    if (status === 'success') {
      setState({ data });
    }
  }, [status, data]);

  return status === 'success' ? (
    <div>Success and use data</div>
  ) : (
    <div>Loading</div>
  );
};
like image 184
Dennis Vash Avatar answered May 16 '26 04:05

Dennis Vash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!