LoseYou21
LoseYou21

Reputation: 65

Passing props from state, into componentDidMount

I have class which makes an api call, and sets the response data as the state value like so

    export class TestClass extends React.Component {
    state = {
       data: null 
    }

    componentDidMount(){
       fetch('http://www.nfl.com/feeds- 
       rs/bigPlayVideos/2018/REG/1.json')
       .then(response => response.json())
       .then(res => this.setState({ data: res.bigPlays }))
    }  

The above code works and sets the state correctly. Then in the render i pass the properties like so.

     render (){
       const {data} = this.state;

       return ( 
        <div>
         <ChildComponent data={data} />
         </div>
        )
        }  

My Child component looks like so

    componentDidMount(){
      const {data} = this.props
     }

The data prop comes in correctly in the render after the page updates but comes in as null in the componentDidMount. I need to do some further state updates, so is there anyway i can get access to the values in the componentDidMount(), if not where would be the best place to do further state logic in the ChildComponent class.

Any help is much appreciated, thanks.

Upvotes: 0

Views: 1115

Answers (3)

Sultan H.
Sultan H.

Reputation: 2938

It's a normal behavior, since what actually happens is as follows: a componentDidMount of any parent component is not invoked unless all of it's childrens componentDidMount is invoked.

So, if component B is a child for component A, component B componentDidMount methods will be invoked before the one for A component since B is a child for A.

Read more about this.

So, if you want to solve this, you can use componentWillRecieveProps lifecycle instead.

    componentWillReceiveProps(nextProps) {
      if(typeof nextProps.data !== 'undefined'){
        this.setState({ data: nextProps.data });
      }
    }

Upvotes: 1

Vencovsky
Vencovsky

Reputation: 31605

What you can do is use componentDidUpdate and check if this.props.data isn't null.

componentDidUpdate() {
    const {data} = this.props
    if(data != null){
        // do what you want
    }
}

But you should also have one more condition to avoid that from happening on every render.

What you can also do is pass a default value to data.

const { data = [] } = this.props // default value is an array.

Upvotes: 1

Sebastian
Sebastian

Reputation: 3594

You probably want to use componentDidUpdate since state.data in the parent is initially null.

If you only want to deal with non-null data only mount the child once data !== null: return <div>{data !== null && <ChildComponent data={data} />}</div>

Upvotes: 1

Related Questions