Home > OS >  update value state in array of objects
update value state in array of objects

Time:12-14

State:

const [tiles, setTiles] = useState(tilesData)

Data inside state: (tilesData)

const defaultValueCard = {
   name: 'Bahamut',
   cardValues: { N: 0, E: 0, S: 0, W: 0 },
   image: 'URL'
}

export const tilesData =
   [
      { tileNumber: 1, card: defaultValueCard },
      { tileNumber: 2, card: defaultValueCard },
      { tileNumber: 3, card: defaultValueCard },
      { tileNumber: 4, card: defaultValueCard },
      { tileNumber: 5, card: defaultValueCard },
      { tileNumber: 6, card: defaultValueCard },
      { tileNumber: 7, card: defaultValueCard },
      { tileNumber: 8, card: defaultValueCard },
      { tileNumber: 9, card: defaultValueCard },
      { tileNumber: 10, card: defaultValueCard },
      { tileNumber: 11, card: defaultValueCard },
      { tileNumber: 12, card: defaultValueCard },
      { tileNumber: 13, card: defaultValueCard },
      { tileNumber: 14, card: defaultValueCard },
      { tileNumber: 15, card: defaultValueCard },
      { tileNumber: 16, card: defaultValueCard }
   ]

The updateTile function receives a tileIndex (numbered between 1-16) and a new card which contains the same data as the defaultValueCard.

How can I inside this function update the state to replace the old card with a new one at the specific index?

const updateTile = (tileIndex, card) => {
 /* take the tileIndex and update the current card with the parameter card */
}

CodePudding user response:

Try this...

const [tiles, setTiles] = useState(tilesData);

const updateTile = (tileIndex, card) => {
 /* take the tileIndex and update the current card with the parameter card */
 const tilesCopy = [...tiles];
 const oldTileIndex = tilesCopy.findIndex(tile => tile.tileNumber === tileIndex);
 // a word of caution, oldTileIndex is undefined if tile with tileIndex DNE
 tilesCopy[oldTileIndex] = {tileNumber: tileIndex, card};
 setTiles(tilesCopy);
 
}
  • Related