Skip to content Skip to sidebar Skip to footer

Cannot Update Particular Property Of Object In React Js Using Setstate

I am fetching data and I have mapped the data to display it. Everything is fine but when I try to update the fetched data (which I have already stored in an array, just want to cha

Solution 1:

The attempt is:

setMyItems( (prevState) => { return [...prevState , {value : { quantity : prevState.quantity - 1 }}  ] } )  } }

Firstly, this is pretty hard to read inline, so I'd move this to a function so you can understand what you're working with.

Next, instead of ...prevState, which spreads the entire previous array and appends a new tail with {value : ...}, find the item you want to mutate by index or id (sort of an application-specific decision--probably id is better) and slice the array into three pieces:

  • The front of the array from 0 to i
  • The item we want to change the quantity of, i
  • The back of the array from i + 1 to the end

This can be done with slicing and spreading to build a new array:

const newArr = [...arr.slice(0, i), arr[i], ...arr.slice(i + 1)];

Last step: manipulating the arr[i] object to adjust the quantity. It looks like quantity is on the top-level, so:

{...arr[i], quantity: newQuantity}

Putting it all together, here's a minimal, runnable example you can apply to your code:

<scripttype="text/babel"defer>const {useEffect, useState} = React;

const mockItems = [
  {id: 11, quantity: 5, item: {title: "foo"}},
  {id: 12, quantity: 1, item: {title: "bar"}},
  {id: 14, quantity: 1, item: {title: "baz"}},
  {id: 15, quantity: 4, item: {title: "quux"}},
  {id: 17, quantity: 3, item: {title: "corge"}},
];
fetch = () =>newPromise((resolve, reject) =>setTimeout(() =>resolve({json: async () => mockItems})
  , 1000)
);

constCart = () => {
  const [items, setItems] = useState([]);

  useEffect(() => {
    (async () => {
      const response = awaitfetch("some endpoint");
      setItems(await response.json());
    })();
  }, []);
  
  constsetQuantity = (id, quantity) => {
    const i = items.findIndex(e => e.id === id);
    setItems(prev => [
      ...prev.slice(0, i),
      {...prev[i], quantity},
      ...prev.slice(i + 1),
    ]);
  };

  return (
    <ul>
      {!items.length ? "loading..." :
        items.map(e =>
          <likey={e.id}><div>{e.item.title}</div><div>
              Qty: {e.quantity}
              <buttononClick={() => 
                  setQuantity(e.id, e.quantity + 1)
                }
              >+</button><buttononClick={() =>
                  setQuantity(e.id, e.quantity - 1)
                }
              >-</button></div></li>
        )
      }
    </ul>
  );
};

ReactDOM.render(<Cart />, document.body);

</script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.0/umd/react.production.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.0/umd/react-dom.production.min.js"></script>

Post a Comment for "Cannot Update Particular Property Of Object In React Js Using Setstate"