'How to change value of dynamic form field?

I don't know why but when I get value from redux, I get the error

TypeError: "price" is read-only

whenever I try to change value of dynamic form field.

const EditProductPrice = () => {
  const { editProductPriceProps } = useSelector(authSelector);
  const [priceFields, setPriceFields] = useState<PriceFieldsProps[]>(
    []
  );

  useEffect(() =>{
    if(editProductPriceProps?.priceFieldProps){
      setPriceFields(editProductPriceProps.priceFieldProps)
    }
  },[editProductPriceProps])

  const onFieldChange = (
    id?: string,
    event?: React.ChangeEvent<HTMLInputElement>
  ) => {
    const newPriceFields = priceFields.map((field) => {
      if (field.id === id) {
        switch (event!.target.name) {
          case "type":
            field.type = event!.target.value;
            break;

          case "price":
            const price = +event!.target.value;
            field.price = price;
            break;
        }
      }
      return field;
    });
    setPriceFields(newPriceFields);
  };
  return (
    <>
     ...
             {priceFields.map((field) => (
                <div key={field.id}>
                      <Input
                        name="type"
                        value={field.type!}
                        placeholder="Type"
                        onChange={(
                          event: React.ChangeEvent<HTMLInputElement>
                        ) => {
                          onFieldChange(field.id, event);
                        }}
                      />

                      <Input
                        name="price"
                        value={field.price!}
                        placeholder="Price"
                        onChange={(
                          event: React.ChangeEvent<HTMLInputElement>
                        ) => {
                          onFieldChange(field.id, event);
                        }}
                      />  
                </div>
              ))}
    </>
  );
};

I removed some code to make it look better, I think the problem come from onFieldChange function. So how can I fix it?

Have a nice day!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source