Home > Mobile >  How to use another state within a setState hook in React?
How to use another state within a setState hook in React?

Time:11-27

I have code that's something like this:

function async example() {
  
  function handleClick() {
     songs = await fetch("/songs")
     setSongs(songs)
  }
  
  setPlaylists(
    <>
      // other element that have trigger handleClick() on click
      {songs}
    </>
  );
}

setPlaylists() has already set its state when the user can click on the element to trigger handleClick(); if setPlaylists() hadn't set its state, the element to click on to trigger the handleClick() would not be present.

Is there a React pattern for this situation? How can I set state of songs and have it update within the state of setPlaylists().

CodePudding user response:

const updatedSongs = async () => {
songs = await fetch("/songs")
     setSongs(songs)
}

function handleClick() {
     updatedSongs()
  }


useEffect(() => { updatedSongs() },[])

CodePudding user response:

I think you are not quite sure of the React Pattern or requirement in general. Also, when you are trying to set state, especially in the setPlaylist, you are using JSX there. Its not the correct usage anyways.

The use of playlists and song states is not good. Please can you present your exact use case?

  • Related