0

when i initialize my state

 constructor(props) {
        super(props);
        this.state = {
          restaurant:this.props.restaurant
        }
    }

console.log(this.state.restaurant) returns: []

"this.props.restaurant" contains data

i need to get the data from props (before rendering) to display them on a table otherwise my table will be empty

Liam
  • 27,717
  • 28
  • 128
  • 190
Nassim
  • 25
  • 7
  • 1
    Setting state in react is not syncronous so console.log won't print updated value, try read this: https://stackoverflow.com/questions/31702861/when-value-is-assigned-to-components-state-why-console-log-prints-the-previous – coglialoro Apr 20 '22 at 12:19
  • not entirely, i need data from props (before rendering) to display them on a table otherwise my table will be empty (console.log is just for testing) – Nassim Apr 20 '22 at 12:47

1 Answers1

0

According to the React lifecycle docs: Click Here

you can use the following code in your class to update before initial render:

constructor(props) {
  super(props);
  this.state = {
    restaurant: null
  };
}

static getDerivedStateFromProps(nextProps, prevState) {
  if (prevState.restaurant !== nextProps.restaurant) {
    return { restaurant: nextProps.restaurant };
  }

  return null;
}
mehrandvm
  • 81
  • 4