score:2
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]);
Source: stackoverflow.com
Related Query
- React hooks state variable not updating after rerender
- React Hooks state not updating variable in view
- React Child Component Not Updating After Parent State Change
- Props not updating when redux state change in React Hooks
- react component state change after ajax call but does not rerender component
- React setState() not updating state after $.ajax() request
- Component does not rerender but redux state has changed via react hooks
- My state is not updating using React Hooks
- React state not updating after a post request?
- Why is the state not updating inside this react Hooks component?
- State not updating after axios call in react
- useSelector function is not updating the state of after dispatch function -react hooks
- React state not updating after async await call
- The state variable returned after using useState react hook shows .map is not a function
- Component state not updating after unchecking checkbox in React
- React state variable not accurate after set state in useState hook
- How to switch the state of buttons in react hooks after updating it through rest api?
- Functional Component does not rerender after state changes [ React ]
- React Hooks Wrapper not getting updated after state change in useEffect
- React 16.8 hooks - child component won't re-render after updating parent state
- React Hooks state is not updating with correct output
- React - changing state not updating elements rendered from variable
- React hooks - setState is not updating the state properties to show sidebar
- Component local state not updating with react custom hooks
- React state not updating after fetch .then statement
- React hooks useState not updating the state
- React Dom not updating after updating a state array
- React state not updating after function call
- React navigation with hooks and header function - state is not updating
- react date array not updating after setting state
More Query from same tag
- Where is the correct place to put event handlers in class components that have constructors?
- How to manage state on a single react element for hover effect?
- Download/Save file in react js
- Use Bootstrap 4 with React
- Why not render I can not access the state array?
- map function reducing index not working (with React)
- React Hook "useState" is called in function
- Use const from another file in Reactjs
- Can you render react component to div with display none?
- How to set a key prop in a select element
- React redux render data
- Is there a way to NOT have the REACT_APP_ env vars prefix?
- How can i use spread only one time?
- Can variable be passing by function (react js)?
- React useEffect and React-Router - Resending an API call in component when user navigates to new page
- Please explain this abbreviated ES6 JSX declaration
- How can I prevent changing sequence of options in my quiz app in react?
- Reactjs Button with dynamic link
- Specify axios response data type
- ReactJS: How to remove row highlight on <TableRow> of Material-UI's <Table>?
- How to fix not re-rendering issue after updating state using a generic function
- Component from an EmotionJS Component library does not receive the Theme prop
- Prevent "React state update on unmounted component" warning when setting state on async callback
- How to fix missing jsx expression container aroud literal string?
- Redirect won't work with react-router v4
- Mapping a JSON const in React.js
- Reactjs set state true or false
- react native - Having static and dynamic elements in FlatList
- Error when use tabIndex in Autocomplete of MUI
- React: How to know which component calls the function