I am working in a React app, at the start of the application I need to make a GET request to a external API that give me some settings, this call I need to make it also when the user login and logout of the system. Currently I have that implemented, now I am not sure where should I call it.
I have a component, and inside I have the method ComponentWillReceiveProps there I am calling the request, however it's calling many many times and this is not what I want. So, which method os the proper to call it? depending of the answer of the API some of the components will be rendered or not. Thank you
I would call the external API in componentDidMount, since it's the recommended place to perform side effects (source).
Once you get the data, you can store it in the component state (or redux, if you have that). And then decide what to render in the render method based on the state.
Example:
class App extends React.Component {
componentDidMount() {
callExternalApi().then(data => {
this.setState({
data: data,
});
});
}
render() {
const { data } = this.state;
if (data === 'render div') {
return <div />;
}
return <span />;
}
}
Something like this for example:
const mapDispatchToProps = dispatch => ({
onLoad: (payload ) => {
dispatch({ type: APP_LOAD, payload});}
});
class App extends React.Component {
componentWillMount() {
this.props.onLoad(Promise.all([reduxagent.get.all()]));
}
}
Here you may load your props within promise right after application starts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With