L
L
lookingfor22021-01-12 22:33:28
React
lookingfor2, 2021-01-12 22:33:28

How to add another object to an object in redux?

There is a common state, it has an object, let's say items

const state = {
    a: "1",
    b: "2",
    items:{
        item1: "Строка 1",
        item2: "Строка 2",
        item3: "Строка 3"
    }
};

In the response from the api, I receive an object
message:{
        item5: "Строка 5",
        item6: "Строка 6",
        item7: "Строка 7"
    }

i need to add message to items without losing everything that was in it, how to do it?

I tried this, but it requires a key, value pair, but I already have a key value in the object
case "SET_DATA": {
    return {
      ...state,
      items: {
        ...state.items,
        ...{action.payload.value}
      },
    };

  };

I tried loops but it didn't work either.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Valery, 2021-01-12
@lookingfor2

case "SET_DATA": {
    return {
      ...state,
      items: {
        ...state.items,
        ...action.payload.value
      },
    };

  };

The problem may be that the keys in the object messagemay match the keys of the object state.itemsand the values ​​will be replaced.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question