Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

update value state in array of objects

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 */
}

>Solution :

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);
 
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading