简体   繁体   中英

Call an action inside the redux reducer

The code in my reducer is as follows:

import {ADD_FILTER, REMOVE_FILTER} from "../../../../actions/types";

const removeFilter = (state, name) => {
    return state.filter(f => f.name !== name);
};

export default function addRemoveFilterReducer(state = [], action) {
    switch (action.type) {

        case ADD_FILTER:
            let nState = state;

            if(state.some(i => i.name === action.searchFilter.name))
                nState = removeFilter(state, action.searchFilter.name);

            return [...nState, {name: action.searchFilter.name, values: [action.searchFilter.values]}];

            //Call another action    

        case REMOVE_FILTER:
            return removeFilter(state, action.searchFilter.name);

        default:
            return state;
    }
}

I have one component showroom and inside the showroom I have Search component and Content component.

Inside search component I handle filtering and I dispatch an action which is handled with this reducer.

After the filter is added I want to dispatch an action with all filters. How can I do that?

That action would be handled with an reducer where I would return only those cars that match search criteria and display them in the content component.

I hope you understand what I wanted to say.

Is this approach good at all?

You may consider to use redux-thunk for this.

You'll have two separate actions, one for adding filter and the other one for making search. Your addFilterAndMakeSearch thunk will be responsible for calling these actions in order. By this way, you won't be need to dispatch an action from your reducer.

// Thunk
function addFilterAndMakeSearch(searchFilter) {
  return dispatch => {
    dispatch(addFilter(searchFilter);
    dispatch(makeSearch());
  }
}

// Action Creator One
function addFilter(searchFilter) {
  return {
    type: 'ADD_FILTER',
    payload: searchFilter,
  };
}

// Action Creator Two
function makeSearch() {
  return {
    type: 'MAKE_SEARCH',
  };
}

In order to make this work, you need to use addFilterAndMakeSearch as your onSubmit handler.

Calling an action is most probably side effect operation. As reducers should follow functional programming principles, I would argue it shouldn't trigger any actions.

To solve your use case, you can still fire two actions from place that triggered change in your reducer. We are doing that sometimes in our app. For example your component can trigger two actions or action can fire two Redux store updates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM