Friday, May 4, 2018

Redux Workflow - Summary

Overview


A blog post to gather my understanding of Redux (redux.js.org/).
Another good explanation can be found at Redux explained.

On button click calling synchronous action

  • The ButtonClickAction() method is called by the onClick attribute of a button and return the action:
    { type :‘BUTTON_CLICK_ACTION’ }
  • Because the action return an object it is automatically dispatched.
  • The dispatching trigger all registered reducers to be called.
  • The dispatching trigger all registered mapStateToProps() to be called. The global state is pass to each mapStateToProps() call. mapStateToProps() return the list of props for its component.
    • If the call return a different result from the previous call, a call to Component.render() will be executed

Summary

  • OnClick
  • Action get dispatched
  • Reducers
  • mapStateToProps
  • Component.render() if needed


On button click calling an asynchronous action

  • Asynchronous action are typically an HTTP call.
  • The Asynchronous action must be a function returning a return function(dispatch) {};
  • The internal function must dispatch 2 synchronous actions, for example requestStartedAction() at first and requestReceivedAction(data) when the data is received, as described below.

//
export function fetchAction(city) {

    return function(dispatch) {

        dispatch(requestStartedAction());

        axios.get(url, config).then(function(data) { 

            dispatch(requestReceivedAction(data));
        });
    }
}

No comments:

Post a Comment