title: Fetch data inside useEffect hook before rendering - React
body: <p>I'm building a prototype that fetches a Spotify user's playlist data in React. The data fetching is done inside a useEffect hook and sets the state of playlists variable. Consequently, I want to render the name of each playlist. However, it seems that the data is only fetched after rendering, causing an issue, because the state is not set before rendering, so playlists variable is undefined. How can I solve this problem while continuing to use React hooks? My code is below.</p>
  <pre><code>import './App.css'
  import queryString from 'query-string'
  import React, { useState, useEffect } from 'react'
  
  const App = () =&gt; {
  
    const [userData, setUserData] = useState({})
    const [accesstoken, setAccesstoken] = useState('')
    const [playlists, setPlaylists] = useState({})
  
    useEffect(() =&gt; {
  
      let parsed = queryString.parse(window.location.search)
      let accesstoken = parsed.access_token
      if (!accesstoken) {
        return
      }
      setAccesstoken(accesstoken)
  
      fetch('https://api.spotify.com/v1/me', {
        headers: {'Authorization': 'Bearer ' + accesstoken}
      }).then(response =&gt; response.json())
      .then(data =&gt; setUserData(data))
  
      fetch(`https://api.spotify.com/v1/me/playlists`, {
        headers: {'Authorization': 'Bearer ' + accesstoken}
      }).then(response =&gt; response.json())
      .then(data =&gt; setPlaylists(data))
  
    }, [])
  
    return(
      &lt;div&gt;
        {accesstoken ? (
          &lt;div&gt;
            &lt;h1&gt;Welcome, {userData.display_name}&lt;/h1&gt;
            &lt;h2&gt;Playlists&lt;/h2&gt;
            &lt;div&gt;
              {playlists.items.map(playlist =&gt; 
                &lt;p&gt;
                  {playlist.name}
                &lt;/p&gt;
              )}
            &lt;/div&gt;
          &lt;/div&gt;
        ) : (
          &lt;button onClick={() =&gt; window.location = 'http://localhost:8888/login'}&gt;Login&lt;/button&gt;
        )}
      &lt;/div&gt;
    );
  }
  
  export default App;
  </code></pre>