Issue
I have a problme updating local state depending on certain condition the state is simply staying the same
data-babel="false">
const [state, setState] = useState({
car: '',
fule: 'Benzine',
});
const handleChange = (e) => {
setState({ ...state, [`${e.target.name}`]: e.target.value });
};
const addCar = (e) => {
e.preventDefault();
if (select === 'type2' && state.fule === 'Benzine') {
setState({ ...state, fule: 'diesel' });
}
console.log(state);
};
Solution
you need to use the old reference as
setState(oldState => ({...oldState, fule: 'diesel'}))
in this way, oldState lost the reference and will be take as new value
Answered By - Black Hole
Answer Checked By - - Marilyn (ReactFix Volunteer)