0

So I wanted to create a universal action creator to manage the items in redux store.

Let's say my redux store looks like this:

one: '',
two: '',
three: ''

My action creators looks like this:

export const setStatus = (name, status) =>{
    return function(dispatch){
        dispatch({
            type: 'SET_STATUS',
            name,
            status
        })
    }
}

and I don't know how to create an action that would manage all of it. Tried

case 'SET_STATUS':{
            return{
                ...state,
                action.name: action.status 
            }
        }

But redux won't let me. Is there any workaround?

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
MazMat
  • 1,904
  • 3
  • 12
  • 24
  • 2
    Possible duplicate of [dynamic keys for object literals in Javascript](https://stackoverflow.com/questions/6500573/dynamic-keys-for-object-literals-in-javascript) – zzzzBov Jun 06 '18 at 18:18

2 Answers2

7

You should use bracket notation to use a variable as a key:

case 'SET_STATUS':{
    return{
        ...state,
        [action.name]: action.status 
    }
}
Chase DeAnda
  • 15,963
  • 3
  • 30
  • 41
3

The think the code is usefull for you.Because you can change some data which you want.good luck

import { createStore } from 'redux'; 

const reducer = (state={
  one: '',
  two: '',
  three: ''
} , action)=>{
switch(action.type){
    case "SET_STATUS":
        state = {
            ...state,
            one: action.payload.one,
            two: action.payload.two,
            three: action.payload.three
        }
    break;
    default: break;
 }
 return state;
}


const store = createStore(reducer);

store.subscribe(()=>{
    console.log(store.getState());
});
const data = {
  one: 'value of one',
  two: 'value of two',
  three: 'value of three'
}
store.dispatch({ 
  type:"SET_STATUS",
  payload: data
});
Araz Babayev
  • 1,752
  • 12
  • 16