I'm having trouble understanding why a list won't update in React. For my website that I'm building, I'm trying to add a 'favorites' button, but when you click the button it updates the state but the changes never re-render in the list. I tried to make a simpler version, but this doesn't work either:
import React, { useState } from 'react';
import './App.css';
function App() {
const [favorites, setFavorites] = useState([]);
function addFavorite(name, id) {
let newFavorites = favorites;
let newFav = {name: name, id: id};
newFavorites.push(newFav);
setFavorites(newFavorites);
}
return (
<div className="App">
<ul>
{favorites.map((val) => {
return(<li key={val.id}><span>{val.name}</span></li>);
})}
</ul>
<button onClick={() => addFavorite("Thing1", 1)}>Thing 1</button>
<button onClick={() => addFavorite("Thing2", 2)}>Thing 2</button>
<button onClick={() => {console.log(favorites)}}>Check</button>
</div>
);
}
export default App;
I can see the state changes in the console when I log them, but the <ul>
element never updates. I've looked online but most of the articles I've found have not been very helpful (I feel the example code I wrote looks a lot like this article.