jhf2
jhf2

Reputation: 135

React props being sent to a component appear as an empty array

I am sending a state to a component as a prop like so:

componentDidMount() {
        axios.get("path/to/data")
            .then(result => {
                this.setState({
                    recievedData: result.data,
                });
            })
            .catch(error => {
                console.log(error);

            });
}


render() {
    return (
        <MyComponent stuff={this.state.recievedData} />
    )
}

When I call console.log(this.state.recievedData) from this file I get the correct output (0: id: 108, name: "foo" __proto__: Object length: 1). However, in the file where I define MyComponent when I call console.log(this.props.stuff) I am told that it is an empty array ([]).

Why is the stuff property not transferring over to MyComponent correctly? Any ideas help. Thanks.

Upvotes: 0

Views: 169

Answers (1)

Ankush Verma
Ankush Verma

Reputation: 778

Inside of MyComponent ,

useEffect(()=>{...},[props.stuff]) 

or if you are using classes

componentDidUpdate(prevProps) {
 if(prevProps.stuff!=this.props.stuff)
      {
          this.setState(...)
       }
} 

Upvotes: 2

Related Questions