2

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.

1
  • Where are you calling fetchUser? Can you post the code for <BaseMap />? Sounds like what they meant is that in <BaseMap /> you should be calling this.props.fetchUser in componentDidMount? Commented Oct 6, 2017 at 20:15

2 Answers 2

4

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>
        );
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.