Home > Enterprise >  Asynchronously update state hook in react
Asynchronously update state hook in react

Time:07-27

I am trying to set a state generated by useState in an async function, but I found if I do like this, react would render my component infinitely.

This is a demo I made

export const App = () => {
    const [nodes, setNodes] = useState([])

    // some async refresh code, like http request, like axios.get("/list-nodes").then ...
    const refresh = async () => {
        let arr = []
        for (let i = 0; i < 10; i  ) {
            arr.push(Math.random())
        }
        setNodes(arr)
    }

    refresh();


    return (
        <div>
            {
                nodes.map(v =>
                    <div>
                        value: {v}
                    </div>)
            }
        </div>
    )
}

In the code, the rendering is continuously happening and the numbers are keeping changing.

May I ask how I am able to set a state in an async function correctly?

CodePudding user response:

You need to use a useEffect hook to fetch data on the first render only. If not, the component fetches at every render, which happens every time the state is updated, which render the component ...

export const App = () => {
    const [nodes, setNodes] = useState([]);

    useEffect(()=>{
      //Self calling async function
      //Be carefull to add a ; at the end of the last line
      (async () => {
        let data = await fetch(url)
        let json = await data.json()
        setNodes(data)
      })()
    },[])

    return (
      <div>
      {  nodes.map(node => <div>Value: {node}</div>)  }
      </div>
    )
}

CodePudding user response:

You can use useEffect

 export default function App() {
  const [nodes, setNodes] = useState([]);
  const refresh = async () => {
  let arr = [];
   for (let i = 0; i < 10; i  ) {
     arr.push(Math.random());
   }
   setNodes(arr);
 };
useEffect(() => {refresh(); }, []);

return (
<div className="App">
  {nodes.map((v) => (
    <div>value: {v}</div>
  ))}
 </div>
);}
  • Related