Elizabeth
Elizabeth

Reputation: 157

Set State Based On Previous State

I have 2 functions that both share an error state. I need the setState in the componentDidUpdate function to update the error state based on whatever the previous state was. This is because currently I can get 2 error states that say the same thing depending on when the lifecycle functions are Called.

state = {
  word: this.props.word,
  error: '',
}


async componentDidMount() {
  const word = this.props.match.params.word;
  try{
    const data = await MerriamAPI.getWordInfo(word);
    if (data.length && data[0].fl && data[0].meta.stems && data[0].hwi.prs[0].mw && data[0].shortdef[0]) {
      this.setState({
        word: word,
        error: '',
       })
      }
    else {
      console.log("Error")
      this.setState({error:'Word Not Found'})
    }
  }
  catch {
    this.props.setModal('Offline');
  }
}


async componentDidUpdate() {
  const word = this.props.match.params.word;
  if (word != this.state.word){
    try{
      const data = await MerriamAPI.getWordInfo(word);
      if (data.length && data[0].fl && data[0].meta.stems && data[0].hwi.prs[0].mw && data[0].shortdef[0]) {
        this.setState({
          word: word,
          error: '',
         })
        }
      else {
        // Need to set this based on previous value
        this.setState({error: 'Word Not Found'})
      }
    }
    catch {
      this.props.setModal('Offline');
    }
    }
  }

Upvotes: 1

Views: 3772

Answers (2)

Luke Storry
Luke Storry

Reputation: 6702

React docs:

How do I update state with values that depend on the current state?

Pass a function instead of an object to setState to ensure the call always uses the most updated version of state).

incrementCount() {
  this.setState((state) => {
    // Important: read `state` instead of `this.state` when updating.
    return {count: state.count + 1}
  });
}

So define a method that can take a state object and return a new state object, and then pass that into setState.

Upvotes: 1

Mario Nikolaus
Mario Nikolaus

Reputation: 2406

setState can be called with function callback that receives previous state as parameter.

this.setState((prevState) => ({
   val: prevState.val + 1)
}));

Upvotes: 3

Related Questions