Answer the question
In order to leave comments, you need to log in
How to add data to an object in REDUX?
Greetings! help me figure it out, I can’t figure out how to add or change data inside an object without overwriting other data
array with data
{"objects":{
"1":{
"data_1":[{"dat":1},{"dat":2)],
"data_2":{"dat":"two"}
},
"2":{
"data_1":[{"dat":1},{"dat":2)],
"data_2":{"dat":"two"}
}
}}
//redux.ts
const initialPartition = {
objects: {}
};
function objectsReducer(state = initialPartition, action) {
switch (action.type) {
case DATA_OBJECT:
const id = action.payload.id;
const key = action.payload.key;
return {
...state, objects: {
[id]: state[key], [id]: {
[key]: action.payload[key]
}
}
};
default:
return state;
}
}
export default objectsReducer;
//action.ts
export const dataObject = object => dispatch => {
dispatch({
type: DATA_OBJECT,
payload: object
});
};
//app
const dataToObject = objectData => dispatch(dataObject(objectData));
function objectToRedux(item, key) {
const objectData = {
id: id,
key: key,
[key]: item
};
dataToObject(objectData);
}
Answer the question
In order to leave comments, you need to log in
The code is noodles, so I can’t answer for sure, but you need something like this:
return {
...state,
objects: {
...state.objects,
[id]: {
...state.objects[id],
[key]: action.payload[key]
}
}
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question