Search code examples
reactjsreact-reduximmer.js

Update the array values using produce in immer


I am trying to update the array values using produce in immer but draft is undefined for me. Can you please tell me what am I doing wrong?

export const getCustomers = (customers) => (dispatch, getState) => { 
  const activeCustomers = produce(customers, (draft) => {
    for (let i = 0; i < customers.length; i += 1) {
      draft.customers[i].position= i;
    }
  });

//I keep getting that error that draft.customers[i] is undefined

What am I doing wrong. Keep getting that error that draft.customers[i] is undefined


Solution

  • Well draft is a clone of customers themselves so it doesn't include costumers, try this:

    export const getCustomers = (customers) => (dispatch, getState) => { 
      const activeCustomers = produce(customers, (draft) => {
        for (let i = 0; i < draft.length; i ++) {
          draft[i].position= i;
        }
      });