Answer the question
In order to leave comments, you need to log in
Why is the state not updated?
Problem sending data to localStorage.
I'm trying to change the data in the internal state, so that later in the same function I can send them to localStorage. For further action. But empty lines come.
state = {
searchWord: "",
newstyle: false,
modal2Visible: false,
inputValue: 1,
favouritesMas: {
id: "",
favTitle: "",
favName: "",
},
};
onChange = (e) => {
this.setState({ searchWord: e.target.value });
};
onChangeNamevalue = (e) => {
this.setState({ favName: e.target.value });
};
addFav = (e) => {
e.preventDefault();
this.setState((prevState) => {
let favouritesMas = Object.assign({}, prevState.favouritesMas);
favouritesMas.favTitle = this.state.favouritesMas.favName;
favouritesMas.favName = this.state.favouritesMas.searchWord;
return { favouritesMas };
});
localStorage.setItem(
this.state.favName,
JSON.stringify(this.state.favouritesMas)
);
this.handleCancel();
};
Answer the question
In order to leave comments, you need to log in
Because writing to a state is not a synchronous operation. Adding to localstorage occurs before writing to the state.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question