Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have multiple states from one reducer in Redux?

Let's say I have the next reducer:

export default (state = [], { type, payload }) => {
    switch (type) {

        case FETCH_POKEMONS:
            const objeto = {};
            payload.forEach((conexion) => {
                objeto[conexion.name] = conexion
            });
            return objeto;

        case FETCH_POKEMON:
        return { ...state, ...payload }

        default:
            return state
    }
}

And I will have a combineReducers like this:

export default combineReducers({
    pokemons: pokemonReducers,
});

But I want to have pokemons state for the FETCH_POKEMONS actions and another state called pokemon for the FETCH_POKEMON acton. How can I derivate two states in the combineReducers from one reducer file?

like image 775
Paul Miranda Avatar asked Jan 27 '23 01:01

Paul Miranda


2 Answers

This is anti pattern, the closest thing to do here would be export 2 reducers from your file, one for each use case

export const reducer1 = (state = [], { type, payload }) => {
    switch (type) {

        case FETCH_POKEMONS:
            const objeto = {};
            payload.forEach((conexion) => {
                objeto[conexion.name] = conexion
            });
            return objeto;

        default:
            return state
    }
}

export const reducer2 = (state = [], { type, payload }) => {
    switch (type) {

        case FETCH_POKEMON:
            return { ...state, ...payload }

        default:
            return state
    }
}
like image 178
Dupocas Avatar answered Jan 28 '23 15:01

Dupocas


If I'm understanding your question correctly, you have two actions, FETCH_POKEMONS and FETCH_POKEMON, and you want them to update two different states, pokemons and pokemon, respectively.

  1. If these are separate states that don't affect one-another, you'll want to create 2 reducer functions, which I'll call pokemon and pokemons, which each manage their own state and then pass those reducers into combineReducers to combine them into a single application-level reducer. I think this is more likely what you're looking for.
  2. If they are not separate states but instead interconnected properties, then use a single reducer, and give the state 2 properties, pokemon and pokemons, and only update the property you are trying to update in each action (i.e. leave state.pokemon with its previous value when performing FETCH_POKEMONS.
like image 33
Austin Avatar answered Jan 28 '23 15:01

Austin