tushar
tushar

Reputation: 791

Correct way to use API with React/Redux

I'm a bit confused about the component lifecycle in React. Consider a component that loads its initial state by dispatching the action, getTodo() and updating the state of the entire app

    componentDidMount() {
      var _this = this;
      axios.get('/api/todo').then(function(response) {
        _this.props.actions.getTodo(response.data);
      }).catch(function(err) {
        console.log(err);
      });
    }

What can I use in componentWillUnmount() to prevent the memory leak? If I choose to do this, how will it be possible to update the state when I come back to the page from another page with this method?

Also, is it a better to just store the props that I need for the page as the state and updating the state instead? My concern with this approach is that it just doesn't update the state of the entire app and other components that might need the same props will have to go through the same unnecessary process, which could be avoided by using the first approach.

Upvotes: 0

Views: 181

Answers (1)

Exayy
Exayy

Reputation: 618

You should avoid doing api call in a component. React offers an interface "nothing" more.

You should dispatch an action. In fact an action creator can be used (check redux-thunk or a redux-api-middleware). Your state app must be hold by redux store, not in your interface.

You probably have a "top" component will is mount only once, it can dispatch this action (action which is able to get initial state)

I hope it will help

Upvotes: 1

Related Questions