-2

I have an Array of Object and I want to change the value of the element.

  const cardObj = [
    {
      id: randomNum(),
      cardName: "My Best Buy",
      totalCreditLine: 1000,
      currentBalance: 400,
      monthlyPayment: 100,
      dueBy: "2022-4-18"
    },
    {
      id: randomNum(),
      cardName: "Amazon",
      totalCreditLine: 2000,
      currentBalance: 1200,
      monthlyPayment: 200,
      dueBy: "2022-4-10"
    },
    {
      id: randomNum(),
      cardName: "Home Depot",
      totalCreditLine: 1500,
      currentBalance: 800,
      monthlyPayment: 300,
      dueBy: "2022-4-15"
    },
    {
      id: randomNum(),
      cardName: "Ebay",
      totalCreditLine: 500,
      currentBalance: 300,
      monthlyPayment: 100,
      dueBy: "2022-3-30"
    }
   
  ];

 const [cards, setCard] = useState([...cardObj]);

I'm trying this but doesn't work:

  const updateDue = (card) => {
  
    cards.map((element) =>{
      if(card != undefined){
        if(element.id === card.id){
          setCard({...cards, element, cardName: 'hello' })
        }
      }
    })
    
  };

The code I need help is this one: setCard({...cards, element, cardName: 'hello' })

If element id === card id change element cardName to 'hello'

1 Answers1

0

You need to change the entire array and then set the value

const updateDue = (card) => {
  if (card) {
    const updatedCard = cards.map(element => {
      if (card.id === element.id) {
        return {
          ...card,
          cardName: 'hello'
        }
      } else {
        return { ...card
        }
      }
    })
    setCard(updatedCard)
  }
}
brk
  • 48,835
  • 10
  • 56
  • 78
  • Almost work, it changes the value but then changes all other names to the same values. But thank you, that gave me a good idea of how to make it work. – Luis Gonzalez Mar 21 '22 at 03:47