Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React hooks state variable not updating after rerender

In the following example I have an array of element (fruits) that I want to update and use the updated array to perform other operations (in this specific case saving the updated list). My understanding was on re rerender the state will update...but it does not here..or there is a delay between state updating and my action.

In the addFruit function I can see 'Peach' being immediately added but the console from the saveFruits function still shows the state fruit remains unchanged. How can I have this updated to use immediately. (And I know in this case I can pass newFruits variable to saveFruits to update but I need fruits to be updated for other places as well).

Forgive me because this is my millionth question about react async states but there's something just not clicking for me yet.

const { useState } = React;

function ParentComp() {
    const[fruits, setFruits] = useState(['Apple', 'Orange', 'Banana', 'Pomegranate', 'Kiwi'])


   const addFruit = () => {
      let newFruits = Object.assign([], fruits)
      newFruits.push('Peach')
      setFruits(newFruits)
      saveFruits()
   }
   
   const saveFruits = () => {
      console.log('API req to save fruits.', fruits)
   }

   return (
    <div>
    { fruits.map( (fruit, key) => <div key={key}>{fruit}</div> ) }
      <button type="button" onClick={addFruit}>Add Peach</button>
    </div>
   )
}

ReactDOM.render(<ParentComp />, document.getElementById('root'))
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

<div id="root"></div>
like image 758
bos570 Avatar asked Apr 08 '19 21:04

bos570


1 Answers

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

useEffect(() => {
    saveFruits();
  }, [fruits]);
like image 176
Atul Avatar answered Oct 19 '22 06:10

Atul