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?
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?
Share Improve this question edited Jun 6, 2018 at 18:18 zzzzBov 179k56 gold badges327 silver badges371 bronze badges asked Jun 6, 2018 at 18:14 MazMatMazMat 2,0943 gold badges15 silver badges27 bronze badges 1- 2 Possible duplicate of dynamic keys for object literals in Javascript – zzzzBov Commented Jun 6, 2018 at 18:18
2 Answers
Reset to default 7You should use bracket notation to use a variable as a key:
case 'SET_STATUS':{
return{
...state,
[action.name]: action.status
}
}
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
});