Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call API on React app start

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

like image 929
Sredny M Casanova Avatar asked Feb 26 '26 23:02

Sredny M Casanova


2 Answers

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 />;
  }
}
like image 62
elas Avatar answered Mar 01 '26 02:03

elas


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.

like image 27
Vyacheslav Avatar answered Mar 01 '26 01:03

Vyacheslav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!