user5797064
user5797064

Reputation:

Where to make Ajax calls in React flux

I have a react js app where the user can create a user and then i make a http post to the backend.

i have a action that looks like this

export function createUser(name, username, password) {
  dispatcher.dispatch({
    type: "CREATE_USER",
    name,
    username,
    password,
  });
}

then in my store i call action and it triggers a function that makes a http post to the backend that looks like this

handleActions(action) {
    switch(action.type) {
     case "CREATE_USER": {
     this.createUser(action.name, action.username, action.password);
      break;
     }
      default:
    }
  }

should i make the ajax call in the store or in the action it self?

Upvotes: 0

Views: 671

Answers (2)

Anton Kononenko
Anton Kononenko

Reputation: 493

First of all you would want redux-thunk which give you opportunity to create actions which dispatches other actions in async way.

After this you can create an action which make a call to server, and on result dispatch new action which would bring to store new data. For example:

getData(param) {
  return (dispatch) => {
    dispatch(dataRequestAction());

    return fetch(`/data/${param}`)
      .then(r => r.json())
      .then(data => dispatch(setDataAction(data)))
      .catch(err => dispatch(errroDuringRataRetrieving(err)))
    };
}

as you see here you have one action (getData) which actually doesn't change the store, but trigger 'dataRequestAction' which put in to store data that request started. Then if request completed one of action can be triggered:

  • setDataAction - if all ok;

  • errroDuringRataRetrieving - if request failed.

In this way you can handle ajax via redux.

Upvotes: 1

Akash Bhandwalkar
Akash Bhandwalkar

Reputation: 901

I think we should have seperate folder called api. There we will have our all api calls. We can inject those file and call those function where we put our functions which call api and respond action.

Upvotes: 0

Related Questions