React app componentDidMount not getting props from parent

Dieguinho picture Dieguinho · Apr 30, 2018 · Viewed 7.3k times · Source

I'm trying to pass props from a parent component to a child component and even though its getting called twice (dunno why, componentDidMount should get called only once) the props seem to be empty.

Parent component:

class Members extends Component{
    constructor(props){
        super(props);
        this.state = {
            interests: []
        }
    }

    componentDidMount(){
        fetch(interestUrl, {
            method: 'GET',
            headers: {
              "Content-Type": "application/json",
              "Authorization": this.props.authToken
            }
        })
        .then((response) => response.json())
        .then((json) => {this.setState({interests: json})})
        .catch(error => {console.log("Error: " + error)})
    };

    render(){
        return(
            <div className="Members-body">
                <div className="Menu-sidebar">
                    <Menu interestList = {this.state.interests}/>
                </div>
                <div className="Main-container">
                    <Main/>
                </div>
            </div>
        )
    }

}
export default Members;

Child component:

class Menu extends Component {
    constructor(props){
        super(props);
    }

    componentDidMount(){
        console.log("interestList: "  + this.props.interestList);
    }

    render() {
        return(
            <div className="Menu-container">
                este es el menu de la aplicacion
            </div>
        )
    }
}

export default Menu;

The console log from componentDidMount inside Menu component prints:

interestList: 
interestList: 

Any ideas to point me in the right direction? Greatly appreciated!

Answer

Dieguinho picture Dieguinho · May 1, 2018

For the answer look at @azium's comments:

no it shouldn't show in the console precisely because componentDidMount only runs once, when the component mounts. when Members component calls setState and pass new props to Menu, it has already mounted so that function and your console log won't be called again with the populated array. you can test this easily by moving your console log into the render function
The component is receiving the props before being created, but the prop is an empty array. You explicitly say that in your Members constructor. Then after Members mounts you call setState which triggers another render with the populated array. Read the docs for a full explanation/