Search code examples
javascriptreduxreact-reduxredux-promise-middleware

In Redux, what is the best way to post data to a server?


I want to post data to a server.. my action is like this:

export function addNewTodo(text) {
  return {
    type: 'ADD_NEW_TODO',
    payload: addNewTodoApi(text)
  };
}

let addNewTodoApi = function(text) {
  return new Promise(function(resolve, reject) {
    //implement fake method for get data from server
    setTimeout(function () {
      resolve({
        text:     text,
        done:     ??,
        assignTo: ??,
        Project:  ??,
        Category: ??,
        id:       ??
      });
    }, 10);
  });
};

I have three way. The first way is import store and and call getState method in my action and the second way is dispatch action in reducer and the last way is pass all data in my action as argument. Which one is correct? I read this question and I'm worried about antipatterns.


Solution

  • You should consider using import { connect } from 'react-redux' and using containers.

    You access your store on function mapStateToProps, you send all your data for your action from the container.

    The signature for it is

    const mapStateToProps = (state, ownProps) => {}
    

    There you get the state which a part could be passed to your action.

    The action perform post to your api using ajax with data you passed from state.

    In your action your could consider using isomorphic-fetch.

    Quick example:

    import 'isomorphic-fetch'
    
    const postData = ()=> ({
      type: types.POST_YOURACTION,
      payload: new Promise((resolve, reject) => {
        fetch(api.postData(), {method: 'POST', }).then(response => {
          resolve(response.json())
        })
      })
    })
    

    In case if you need to access the store directly you could use .getState(), accessing state directly could be considered an anti-pattern but it really depends on your architecture design. I would suggest to look look at mapStateToProps.

    Example of how to access your store.

    import store from 'app/store'
    store.getState().yourReducer.data