3

How do I change the value of inCart to true based on id, like i have a function that will provide a id , and base that id i want to change the first objects inCart value to true or the 2nd object inCart value

I tried like this:

setInfo({ info[id].inCart: true })
/*Note: id is a parameter that hold the number like 1 or 2 etc*/

const [info, setInfo] = useState([
        {
            id: 1,
            title: "Google Pixel - Black",
            inCart: false
        },
        {
            id: 2,
            title: "Samsung S7",
            inCart: false,
        }  
])
2
  • What is the id in info[id] refer to??Index or the id of Object Commented Sep 24, 2019 at 11:54
  • i am using id as index to refer that object Commented Sep 24, 2019 at 11:56

1 Answer 1

3

Try Array#find to find the reference, mutate it and return a shallow copy of your state.

const [info, setInfo] = useState([
  {
    id: 1,
    title: 'Google Pixel - Black',
    inCart: false
  },
  {
    id: 2,
    title: 'Samsung S7',
    inCart: false
  }
]);

const idToChange = getId();

setInfo(info => {
  const matchingCart = info.find(cart => card.id === idToChange);
  matchingCart.inCart = !matchingCart.inCart;
  return [...info];
});
Sign up to request clarification or add additional context in comments.

1 Comment

Generally, I use map and return a new array but I also like this logic if you need to mutate your state in your control. Maybe there could be an explanation of why we return a shallow copy of our state since if we don't do that react don't rerender the component.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.