I am new to react/javascript paradigm. So i have picked up a course a freecodingcamp.org to start learning. I am currently getting an error at this implementation (https://youtu.be/kqi4gPfdVHY?list=PLmexTtcbIn_hvPcUm3oAufCtH7dwNAC-g&t=2447)
Here is the code for addLike
button. The error is that when I "update" the song, the new updated songs list doesn't have all values (the size of the array is same but first element is 0). Specifically these two lines in the code
const songData = await API.graphql(graphqlOperation(updateSong, {input: song}))
const songList = [...songs];
Now, I am no javascript expert so i am not sure why ...
syntax isn't copying the error to new array. it just copies one element and thats it. what am i doing wrong?
FULL CODE
function App() {
const [songs, setSongs] = useState([])
useEffect(() => {
fetchSongs()
}, [])
const fetchSongs = async () => {
try {
const songData = await API.graphql(graphqlOperation(listSongs));
const songList = songData.data.listSongs.items;
console.log('song list', songList);
setSongs(songList)
} catch (error) {
console.log('error on fetching songs', error)
}
}
const addLike = async(idx) => {
try {
const song = songs[idx];
song.like = song.like + 1;
delete song.createdAt;
delete song.updatedAt;
const songData = await API.graphql(graphqlOperation(updateSong, {input: song}))
const songList = [...songs];
songList[idx] = songData.data.updateSongs;
setSongs(songList);
} catch (error) {
console.log('error on adding like to the song', error)
}
}