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>
You can try with useEffect which will give updated state whenever there will be update.
useEffect(() => {
saveFruits();
}, [fruits]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With