Fetch from componentDidMount in React JS

Viewed 520

I have a component <BaseMap /> and a fetch line fetchUser={this.fetchUser.bind(this)} that I used immidiatelly after the BaseMap in the render method (eg. <BaseMap fetchUser={this.fetchUser.bind(this)}/>).

However, somebody advised be that I should put it in componentDidMount instead. But how should I do it? I can't just copy fetchUser={this.fetchUser.bind(this)} into componentDidMount.

2 Answers

From what I understand, your components are set up as follows:

class Parent .... {
    ....
    fetchUser(){ 
    ....
    }

    ....
    render(){
        return ( 
        ...
            <BaseMap fetchUser={this.fetchUser.bind(this)}/>
        ...
        );
    }
}

class BaseMap .... {
    ....
    render(){
        let user = this.props.fetchUser();
        return ( 

            <div> { ...use user here ... }</div>

        );
    }
}

Please correct me if I am wrong.

What you are being advised to do is to take the call to fetchUser out of BaseMap components render method and move to its componentDidMount method. Then store the user in the state of the component and use it from there.

class BaseMap .... {
     constructor(props){
        super(props);
        this.state={user:null};
     }

    componentDidMount(){
        let user = this.props.fetchUser();
        this.setState({user:user});
    }

    render(){
        return ( 
            <div> {this.state.user?  
                       ...use user here ...
                        : "loading data"
            }</div>
        );
    }
}

Move your fetchUser method to BaseMap component and then call the method in componentDidMount as this. fetchUser(). Else pass method as props and access it in your target component.

Related