1

I am creating a useReducer that, e.g., sets the price of an item.

const reducer = (state, action) => {
    switch (action.type) {
      case 'SET_PRICE': 
        return {
          ...state,
          price: action.payload,
        }
      default:
        return state
    }
  }

I now have to have multiple of these SET_PRICE, as I have hundreds of products, so I started writing

case 'SET_PRICE_0': 
        return {
          ...state,
          price_0: action.payload,
        }
case 'SET_PRICE_1': 
        return {
          ...state,
          price_1: action.payload,
        }
      ...

I can see that there's something wrong if I write over 10 of these, let alone 100... Is there an alternative to write less code?

uber
  • 4,163
  • 5
  • 26
  • 55
  • please post the initial state you are using + how come you want to set the price of all products at once ? either you should have in the action each product with the price or when the user types the price for each product you set it – Incepter Apr 06 '20 at 16:32

2 Answers2

0

You may wanna refactor your code. This approach, case 'SET_PRICE_1, will not scale. Can you post an example of Api response? Depending on your data structure, you should have something like:

products: [
  {
    productName: 'productName',
    price: '$$$',
  },
]

or maybe

 products: {
   [productName]: {
     price: '$$$',
   } 
 }

in case, you just need the product price (this will not scale too),

  productPrices: {
    [productName]: '$$$'
  }
Constantin
  • 3,655
  • 1
  • 14
  • 23
0

I believe the issue is not with the reducer you have mentioned, but the way you're using it. While rendering the products, you should use useReducer hook with the first reducer (the one with SET_PRICE) while mounting each product component.

Here's a dummy implementation:

const ProductComponent = () => {
    const [price, setPrice] = useReducer(reducer, initialState);
    return (
        <div> ... </div>
    );
};

And then you can map on your products list with this component.

You can also refer to this detailed article on different useReducer recipes: https://medium.com/crowdbotics/how-to-use-usereducer-in-react-hooks-for-performance-optimization-ecafca9e7bf5