K
K
Kirill2022-04-20 17:07:47
redux
Kirill, 2022-04-20 17:07:47

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"}
  }
}}

I can't overwrite/add data_2 without losing data from data_1 and vice versa, redux stupidly overwrites everything after "1":{

//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);
        }

please tell me what is wrong

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2022-04-20
@KirillSPB777

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 question

Ask a Question

731 491 924 answers to any question