user3139602
user3139602

Reputation: 51

Fetching data in Redux

I have a component in a redux app that needs to fetch data from a remote server.

Where is the proper place to make the call and handle all of its logic? action creator? smart component in a lifecycle method like componentDidMount?

Upvotes: 2

Views: 304

Answers (3)

1ven
1ven

Reputation: 7026

It depends on your situation.

If you are building application using smart / dumb components concept, the best place, in my opinion, to perform api calls - is componentDidMount lifecycle callback:

// SomeComponent.js

// ... other methods ...

constructor(props) {
  super(props);

  this.state = {
    todos: [],
  };
}

componentDidMount() {
  // `axios` is ajax library
  axios.get('/todos')
    .then(todos => {
      this.setState({
        todos: todos
      });
    });
}

Upvotes: 1

Jackson
Jackson

Reputation: 139

componentDidMount is the correct place to make an API call. Sometimes you might want it in componentWillMount depending on how early you want the data.

I would also recommend looking into redux-thunk which can help with creating actions that fetch data.

https://github.com/gaearon/redux-thunk

Upvotes: 1

user5466293
user5466293

Reputation:

As written in the official docs: https://facebook.github.io/react/tips/initial-ajax.html

Fetch data in componentDidMount. When the response arrives, store the data in state, triggering a render to update your UI.

Upvotes: 0

Related Questions