escplat12
escplat12

Reputation: 2521

Fetch from componentDidMount in React JS

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.

Upvotes: 2

Views: 566

Answers (2)

Elumalai Kaliyaperumal
Elumalai Kaliyaperumal

Reputation: 1520

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.

Upvotes: 1

palsrealm
palsrealm

Reputation: 5243

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>
        );
    }
}

Upvotes: 4

Related Questions