Home > other >  Update Values of Multiple Array in Redux
Update Values of Multiple Array in Redux

Time:02-23

I'm updating an array and I wanted to update the productCode based on the given newCode response. This is by clicking the 'CREATE ALL PRODUCTS' button. I'm thinking that the problem is on the reducer. It's currently not updating the productCode and newProductCode

Tip: productIndex is the key to finding it

Click Here: CODESANDBOX

Action

export const createAllProducts = (products) => async (dispatch) => {
  try {
    dispatch({
      type: appConstants.CREATE_ALL_PRODUCTS_REQUEST
    });

    const responses = [
      {
        config: null,
        data: {
          newCode: "NEW_AA"
        },
        headers: null
      },
      {
        config: null,
        data: {
          newCode: "NEW_FF"
        },
        headers: null
      },
      {
        config: null,
        data: {
          newCode: "NEW_GG"
        },
        headers: null
      }
    ];

    const finalResponses = responses.map((product, index) => ({
      newProductCode: product.data.newCode,
      productCode: product.data.newCode,
      productIndex: products[index].productIndex
    }));

    console.log(finalResponses);

    dispatch({
      type: appConstants.CREATE_ALL_PRODUCTS_SUCCESS,
      payload: finalResponses
    });
  } catch (error) {
    dispatch({
      type: appConstants.CREATE_ALL_PRODUCTS_FAILURE
    });
  }
};

Reducer

case appConstants.CREATE_ALL_PRODUCTS_SUCCESS:
  const updatedProducts = state.products.map((product, index) => {
    const found = action.payload.find((el) => el.productIndex === index);

    return found
      ? {
          ...updatedProducts,
          productCode: found.productCode,
          newProductCode: found.newProductCode
        }
      : product;
  });
  return {
    ...state,
    isCreatingAllProducts: false,
    products: updatedProducts
  };

CodePudding user response:

The issue is with the reducer

case appConstants.CREATE_ALL_PRODUCTS_SUCCESS:
  return {
    ...state,
    products: state.products.map((product, index) => {
      const found = action.payload.find((el) => el.productIndex === index);
      console.log(found);

      return found
        ? {
            ...product,
            productCode: found.productCode,
            newProductCode: found.newProductCode
          }
        : product;
    })
  };

CodePudding user response:

You used reduce methods with the initial value state, which is the actually old state. Consider this example:

const state = { history: null }
const payload = [ 'hello', 'equal' ]

//your current reducer
const newState = payload.reduce((acc, cur) => { acc[cur] = cur; return acc } , state)


//the state reference point to the same obj, then redux will not trigger re-render
console.log(newState === state) // true

  • Related