reactjsreact-nativereduxredux-sagaredux-actions

how can i replace my redux actions and use create actions library?


I'm looking for redux libraries that can reduce redux boilerplate and recently i discovered reduxsouce and redux-actions which helps in reducing action object code rewrite. In all my previous projects for action definition i would creat one file for all actions and actions looks like this

export function requestInit() {
  return {
    type: types.REQUEST_INIT,
    payload: {
      loading: true,
    },
  };
}

now if i want to remove action definition and switch to "createaction" how can i replace this with createaction method from redux-actions?

also how do i handle or "put" other fail or success action from saga (generator function)?


Solution

  • Looking at the redux-action docs, the actions definitions should look like this:

    import { createAction, handleAction } from 'redux-actions';
    const defaultState = { loading: false };
    
    export const requestInit = createAction(types.REQUEST_INIT); // creates an action creator
    
    // Define your reducer here, as second argument. 
    // First argument is the action type, third is defaultState
    handleAction(
      types.REQUEST_INIT,
      (state, action) => ({
        loading: action.payload.loading
      }),
      defaultState
    );
    ...
    // in saga.js or other place you want to use the action
    requestInit({ loading: true }); 
    

    In the same manner you could add other actions to handle your requests. Dispatching and handling errors should be exactly as it is with ordinary actions, i.e.:

    yield put({ type: response, payload: {...} });
    

    Hope that's helpful.