Search code examples
javascriptreactjsreact-props

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.


Solution

  • Inside of MyComponent ,

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

    or if you are using classes

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