0

I am doing the .get() request in Jquery and updated the state as well.

My question is:

Why am I not able to see the data in console.log(this.state.storage) in componentWillMount() as well as componentDidMount() but I do get the output in render()?

Also I will need to do operations on fetched data, in which lifecycle I should do it?

constructor() {
  super();
  this.state = {
    storage: []
  }
}

componentWillMount() {
  $.get('data.csv', (data) => this.setState({
    storage: data
  }));
  console.log(this.state.storage); //No Output
}

componentDidMount() {
  console.log(this.state.storage); //No Output
}

render() {
    return ( 
    <div >{this.state.storage}</div> //Do get the Output
    );
hemantmetal
  • 107
  • 10

1 Answers1

1

this.setState is asynchronous in how it updates the component state; documentation here. If you want to see the changes effected by this.setState then you have to pass a callback to the function call

Also, you can do your operations in the callback of the $.get method as shown below

constructor() {
  super();
  this.state = {
    storage: []
  }
}

myCustomOperations = (data) => {
  // do custom operations here with data
}

componentWillMount() {
  $.get('data.csv', (data) => {
    this.myCustomOperation(data);
    this.setState({
      storage: data
    }, () => {
      console.log(this.state.storage); // correct output
      // this.myCustomOperation(this.state.storage) // if you want to do the custom operation after the data has been put into the state
    });
  });
  console.log(this.state.storage); //No Output
}

componentDidMount() {
  console.log(this.state.storage); //No Output
}

render() {
    return ( 
    <div >{this.state.storage}</div> //Do get the Output
    );
Raghudevan Shankar
  • 1,083
  • 9
  • 18