Search code examples
javascriptnode.jsreactjsnext.js

Fetch is not workin, Next js


I have an issue with Next.js. The problem is that when trying to make a fetch to an API request, I encounter this: consola and I'm not sure why. I've already deleted the database of my API, so it shouldn't be showing me that. When trying to access the same route with Postman, it perfectly reflects the data. this is my code:

async function loadImg(){
  const res = await fetch("http://localhost:4000/api/getImages")
  const data = await res.json()
  return data
}


export default async function ImgPage() {
  const imgs = await loadImg()
  console.log(imgs)

  return (
    <div>
      {imgs.map((img)=>(
        <div key={img._id}>

          <h3>{img.date}</h3>
          <img src={"http://localhost:4000/files/"+img.filename} alt={img.originalname}></img>
        </div>
      ))}
    </div>
  )
}

What I hope for is that it reflects my API data. Do you know if Next.js has some sort of internal memory or something that could be showing me that?,I created the API myself, my backend (api) is at localhost://4000/api/getImages and my app is at localhost://3000/images.


Solution

  • I have change this part of the code, fetch('localhost:4000/api/getImages',{cache:"no-store"}), on line two. It seems that if you use a fetch, it gets stored in the cache, and how did this affect me? For some reason, it was fetching cached data, and that's why it wasn't making the request to my API. As a result, it wasn't reflecting the data I was fetching from my API. You can read more about this here: https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#opting-out-of-data-caching

    async function loadImg(){
      const imgGet= await fetch('http://localhost:4000/api/getImages',{cache:"no-store"})
      const imgs= await imgGet.json()
      return imgs
    
    }
    
    
    export default async function ImgPage() {
       const imgs = await loadImg()
    
      
       return (
        <div>
          {imgs.map((img)=>(
            <div key={img._id}>
    
              <h3>{img.date}</h3>
              <img src={"http://localhost:4000/files/"+img.filename} alt={img.originalname}></img>
            </div>
          ))}
        </div>
      )
    }