Glenncito
Glenncito

Reputation: 930

I am unable to update my state in Redux with dispatched action (using Redux-starter-kit)

I am very new to Redux and React-Native. I have a state which contains an array of Expense objects. One of the attributes is comment, which I am trying to update from a modal.

I think I have my code mostly right, but for some reason, the state is not updating with the newly updated item.

Modal Component code below:

 const expense = useSelector(state => state.expenses.model.find( expense => expense.id === expenseId ))

  const updateExpense = (updatedExpense) => dispatch(model.actions.updateExpense(updatedExpense))
  const addComment = () => {
    const updatedExpense = {
      ...expense,
      comment: "hi"
    }
    updateExpense (updatedExpense)
  }

Just to note,index is an attribute of the expense object.

and then here is where I set up my data model store and reducers:

    export const model = createSlice({
  slice: "model",
  initialState: [],
  reducers: {
    fetchSuccess: (state, { payload }) => (state = payload),
    updateExpense: (state, {payload}) => (
      console.log ("...State: ", state),
      console.log ("Payload", payload),
      state = [
        ...state.slice(0,payload.index),
       payload,
        ...state.slice (payload.index)
    ],
   /* state = {
...state, [payload.index]:{
  ...state[payload.index],
  comment: payload.comment*/
    console.log ("State: ", state)
    )
  }
});

My logs tell me that payload contains the correct information, its just not updating the state.

Cheers.

Upvotes: 1

Views: 85

Answers (2)

Dave Newton
Dave Newton

Reputation: 160321

It looks like you're using redux-starter-kit, but you don't say you are or aren't. If you're not, ignore this answer.

Right now you're setting state in your reducer: state is a reference local to the reducer. You either need to modify a state property, or return the new state, as described in the r-s-k docs, e.g.,

updateExpense: (state, { payload }) => [
  ...state.slice(0, payload.index),
  payload,
  ...state.slice(payload.index)
]

Same goes for fetchSuccess.

Upvotes: 2

Steven Koch
Steven Koch

Reputation: 797

You should return the changed state your code it's not returning the state

Upvotes: 0

Related Questions