N
N
newhack2020-04-26 19:57:05
JavaScript
newhack, 2020-04-26 19:57:05

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

2 answer(s)
M
McBernar, 2020-04-26
@newhack

Because writing to a state is not a synchronous operation. Adding to localstorage occurs before writing to the state.

N
no-taktik, 2020-04-26
@no-taktik

You can move saving to localStorage to the second argument of setState

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question