score:2

Accepted answer

It's not accurate to console.log fruits because the reference to fruits is still referring to the fruits you had before you called setFruits.

If we console.log newFruits, which has the change, it would be more accurate of what is happening.

EDIT: It's probably better to useEffect as what @Atul suggested though.

It sometimes helps to visualize how this is done in old React classes. In old React classes the equivalent of this is this (to some degree not actually but close enough to illustrate the point) (Read more: https://reactjs.org/docs/hooks-state.html)

class ParentComp extends React.Component {
  constructor() {
    super();
    this.state = {
      fruits: ['Apple', 'Orange', 'Banana', 'Pomegranate', 'Kiwi']
    };
  }

  addFruit = () => {
    let newFruits = Object.assign([], this.state.fruits);
    newFruits.push('Peach')
    this.setFruits(newFruits)
    this.saveFruits();
  }

  setFruits = (fruits) => {
    this.setState({
      fruits
    });
  }

  saveFruits = () => {
    console.log(this.state.fruits);
  }

  render() {
    return ( 
        <div> 
         {this.state.fruits.map((fruit, key) => {
          return (<div key={key}>{fruit}</div>) })} 
          <button type="button" onClick={this.addFruit}>Add Peach</button>
        </div>
    );
  }
}
ReactDOM.render(<ParentComp /> , document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

We get the same problem above but it might be a little clearer. The setState for fruits does get called but the console.log happens before the state/render change happens so this.state.fruits is still referring to what was in the state before.

I highly recommend reading React hooks: not magic, just arrays to get a better sense of what goes on behind the scenes of hooks. It helps explain it a lot.

score:12

You can try with useEffect which will give updated state whenever there will be update.

useEffect(() => {
    saveFruits();
  }, [fruits]);

Related Query

More Query from same tag