简体   繁体   中英

Array in state not updating after useEffect runs in React

I'm extremely new to React.js. I am trying to change a variable recepies which is in state using hooks. Below is my code snippet:

import React, { useState, useEffect } from 'react';
import './App.css';

function App() {

const [recepies, setRecepies] = useState([]);

useEffect(()=>{getRecepies()}, []);

//const example = Some valid API URL


  const getRecepies = async () =>{
    const response = await fetch(example);
    const data = await response.json();

    //data.hits is an array of 10 objects
     setRecepies(data.hits);

     console.log(recepies);
    // prints nothing

  }

  return (  
    <div className="App">
    </div>
  );
}

export default App;

The problem is that setRecepies is NOT updating the recepies state. Why is that? data.hits is a valid array that has 10 objects that I'm fetching using an API.

recepies is a local const . It will never change, and that's not what setRecepies is trying to do. Putting a log statement where you've put it can only ever log out what recepies was equal to when getRecepies was created.

The purposes of setRecepies is to tell react to rerender the component. When that second render happens, a new local const will be created which will get the new value. This variable is visible to anything created on that second render, not to things created on the first render. So if you want to see the new value, put your log statement in the body of the component so you can see what value it's rerendering with.

const [recepies, setRecepies] = useState([]);
console.log('rendering with', recepies);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM