React error not a function even with me console logging the value?

Viewed 55

I am a beginner working on his first MERN project, I created an API for music, added artist, album,... and I have mongo db in the backend and I am having a full crud app with google firebase authentication, the problem is I decided to use audio db API to be able to have a bigger library and to implement more functionality at more ease, I can fetch the API and console log the results but in react when I decide to map it I get the not a function error or cannot map undefined, for both errors prior to writing the code I had console logged both value and it was a valid one. I am also having an issue with authentication that is causing me to not be able to display any information on page load and this is why I decided to go with the API so that way I won't miss with the authentication functions and I can just fetch data for now and later on start pushing to mongo db but I need to display any data on screen first. any ideas what might be wrong ??! this is the code for my component only git hub frontend: https://github.com/moeabraham/proj3 git hub backend: https://github.com/moeabraham/proj3-backend

    function AlbumSlide ()  {

    const [initData, setInitData] = useState({
        results: ['']
      })
      useEffect(()=> {

          async function getInitData(){
              
            const init = await fetch('https://www.theaudiodb.com/api/v1/json/523532/searchalbum.php?s=eminem').then(res => res.json())
    
            setInitData(albums =>({
              ...albums,
              init
            }))
            // console.log(init)
            console.log(initData.init.album)

        
          }
          getInitData()

        
    
      },[])


      

    return  ( 
      <>
      <div className="albumSlide">     
         {initData.init.albums.map((album, idx)=>{
           <p key={idx}>{album.strAlbum}</p>
         })}
</div>

      {/* <section className="albumSlide">
                  <article class="card"  key={idx}> 

      </section> */}
      
      </>
      )
}    


    
export default AlbumSlide;
1 Answers

You need to guard the access to the state value, which takes some time to set (ajax is async, setter is async)

Try something like this in your returned jsx

return  ( 
  <>
    <div className="albumSlide">     
      {initData?.init?.albums && initData.init.albums.map((album, idx) =>
        <p key={idx}>{album.strAlbum}</p>
      )}
    </div>
  </>
)
Related