Need help updating redux state in the reducer

The redux state that i want to update look like this:


const store = createStore(allReducers, {
    todos: [{
    id: "gpja3p5vz8vz6734p6d3is"
    items: [{data: "d", stroke: 0, id: "dme30447zagz2jl6a2ipgo", todos_id: "gpja3p5vz8vz6734p6d3is"}]
},
{
    id: "fasfasfdgsh"
    items: [{data: "d", stroke: 0, id: "dme30447zagz2jl6a2ipgo", todos_id: "gpja3p5vz8vz6734p6d3is"}]
}]
})

I have an array with objects (action.payload).I want to push every single one of these objects to the end of the todos items array

arr[
{data: "d", stroke: 0, id: "dsa", todos_id: "gpja3p5vz8vz6734p6d3is"}
{data: "d", stroke: 0, id: "gfds", todos_id: "gpja3p5vz8vz6734p6d3is"}
{data: "d", stroke: 0, id: "gdfs", todos_id: "gpja3p5vz8vz6734p6d3is"}
]

I been trying to solve this for so many hours but I cant solve it so can someone please help me?

I have tried alot

case 'newItems':
   

    let state = [
        ...rState.map(todo => {
            if (todo.id === 'm8o99m6bb3n4jbms87ln') {
                return [...todo.items, ['asd']]
                
            } else return todo

        })
    ]
        return state
case 'newItems':
            var todoItem = rState.map(todo => {
                if (todo.id === action.payload.todos_id) {
                    return {
                        ...todo,
                        items: action.map(item => {
                                return {
                                    ...item,
                                    item  

                            }
                        })
                    }
                }
                return todo
            })
            return todoItem

and so on

You’re close.

case "new items":
  return {
    ...state,
    todos: state.todos.map(todo => {
      const toMerge = action.payload.filter(({todos_id}) => todo.id === todos_id);
      return {
        ...todo,
        data: [...todo.data, ...toMerge]
      };
    })
  }

I’d seriously advise reading the pages in the Redux docs about normalizing data and apply what they advise, because it’s incredibly difficult to deal with the data you have there. It is not pleasant dealing with deeply nested state in Redux, and you need to flatten that data out, the data structure you’ve got is not one that lends itself to dealing with immutable updates.

Thank you for the answer. It still doesnt work. the app/screen gets all white after this update is done :s

Yes, those nested states are not fun at all. I just cant make them work but my coding level is very low so maybe thats why.
I will read the docs later for upcoming projects cause as it is now does not work in the long run

1 Like