Search code examples
reactjssetstate

how can I retrieve the updated state element in componentDidMount in reactjs


I'm trying to retrieve the updated state value in componentDidMount() to append that value as a parameter in fetching data from an API. I have created this handleChange() method from where I can update the state with current required values. The problem is componentDidMount() hits before the first rendering of page so it shows me null value if I try to fetch the state value. I do not know how can I mention that I want to fetch the value after second rendering.

constructor(props) {
    super(props)
    this.state = {
      names: [],
      equipments: [],
      isLoaded: false,
      inputValue: null,
      siteID: ''
    };
  }
handleChange = selectedOption => {
    let { inputValue, stateID } = this.state;
    this.setState({ ...this.state, inputValue: selectedOption });
    console.log(`Option selected: ${selectedOption.value}`);
    let selectedElement = selectedOption.value;
    let filteredID = stateData.filter(name => name.name == selectedElement)
      .map((name) => {
        return name.id
      })
    // console.log(filteredID[0]);
    this.setState({ stateID: filteredID[0] })
    localStorage.setItem(stateID, filteredID[0]);
  };

ComponentDidMount() {
    const token = localStorage.getItem("token");
    console.log("Inside Component Drop Down =" + token);

    // let stateid = this.state.stateID;
    // console.log("stateid" + stateid);

    let stateid = 23301;//
    let url2 = `https://applicaiton/api/helpdesk/get_personID/?stateid=${stateid}`;
    fetch(url2, {
      method: "GET",
      headers: { "Content-Type": "application/json", "Authorization": `Token ${token}` },
      credentials: "same-origin"
    })
      .then((results1) => {
        return results1.json();
      }).then(data2 => {
        this.setState({
          isLoaded: true,
          equipments: data2,
        })
      });
  }


Solution

  • Rather than componentDidMount, consider using the React lifecycle method componentDidUpdate as follows:

    componentDidUpdate(prevProps, prevState, snapshot) {
       // Make comparison between this.state and prevState 
       // as necessary to retrieve proper value
    }