0

I am getting an error while I am trying to use base64 images I have fetched from backend. All the backend APIs are working properly. I am getting all the base64 images as response also, but images are not appearing and I am getting this error too. Can anyone fix this? Thank you in advance. :)

useEffect hook:

 useEffect(()=>{
        const config={
          headers:{
            "Content-Type":"application/json",
            Authorization:`Bearer ${localStorage.getItem("token")}`
          }
      
        }
    axios.get(`/api/user/public/getalbums/${id}`,config ).then(({data})=>{
      setAlbum(data);
      const arr=[];
      for(let i=0;i<data.length;i++){
        axios.get(`/api/user/private/readimage/${data[i].fileUrl}`,config).then((res)=>{
       console.log(res.data);
       console.log("res");
        arr.push(res.data);
        
        // setPhotos([...photos,res.data])
        
        })
      

      }
      console.log(arr);
      setPhotos(arr);

        // setPhotos([...photos,res.data])
        
    
    }
    ) 

      },[])

Image:

{album.length>0 && album.map((data,ind)=>{
          return(
            
            <div key={ind}>
            <div className='album-card-1' ><img className="album-card-img" src={`data:image/jpg;base64, ${photos.length>0 && photos[ind]}`}  onClick={()=>{
                navigate(`/artist/${id}/user/album/${data._id}`)
             }}/></div>
          </div>
           
          )
        }
        )}

Error:

data:image/jpg;base64, false
net::ERR_INVALID_URL

1 Answers1

0

Your HTML code is correct, it should be showing the correct image if the base64 is coming correctly. Probably your error is on your logic related to the album and photos arrays. Please add an example of the values of these arrays (The console.log that you're printing).

Also, you can add a validation that check if the base 64 is not false before rendering your JSX:

return album.length > 0 && album.map((data, ind) => {
  return photos.length > 0 && photos[ind] && (
    <div key={ind}>
      <div className='album-card-1'>
        <img className="album-card-img" src={`data:image/jpg;base64, ${photos[ind]}`} onClick={() => navigate(`/artist/${id}/user/album/${data._id}`)}/>
      </div>
    </div>
  )
});