Coming soon - Get a detailed view of why an account is flagged as spam!
view details

This post has been de-listed

It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.

0
Why is this code not working? Javascript, React
Post Flair (click to view more posts with a particular flair)
Post Body

Hi all, not really sure if this is the right sub but I'm stuck and don't really know where to turn.

I'm implementing a way to make a list from the user input and would like to add a button to delete the corresponding array. I can Add the button no problem (The Button is a component of it's own that's why it's a <Button /> element) but on the onClick I can't get it to work.

I'm trying to get the corresponding array index deleted with a click on the button. However, it doesn't work.

My code the following:

//The hooks for this code

`const [songsArray, updateSongsArray] = useState([])
const [newSong, setNewSong] = useState('')`

//function to make the initial songsArray

`function pushToSetlist(e){
e.preventDefault()
updateSongsArray((songsArray) =>[...songsArray, (newSong)])
setNewSong('')
}
`

//the jsx that implements the array.map on the page

`<ol>
{songsArray.map((songArray, index) =>{
return
<li key={index}>{songArray}
<Buttontype="button"onClick={() =>{songArray.splice(index, 1, 0)}}buttonText="X"/></li>})}
</ol>
`

If anyone could helpt me, or point me in the right direction I would be grateful.

Solved:

For some reason the .splice method does not agree with useState and the slice method is encouraged. I don't fully understand WHY this works though, so if anyone can elaborate I would appreciate it.

` function deleteButtonHandler(index) {
if (songsArray.length === 1 && index === 0) {
updateSongsArray([])
} else {
updateSongsArray([...songsArray.slice(0, index), ...songsArray.slice(index 1)])
}
}
`

`{ (songsArray.length >= 1) ?
songsArray.map((songArray, index) => {
console.log(index)
return <li>{songArray}
<Button type="button" onClick={() => {deleteButtonHandler(index)}}
buttonText="X"
/>
</li>
})
:
<li>There are no songs yet</li>
}

`

Author
Account Strength
100%
Account Age
3 years
Verified Email
Yes
Verified Flair
No
Total Karma
20,361
Link Karma
45
Comment Karma
20,233
Profile updated: 4 days ago
Posts updated: 1 year ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
2 years ago