skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    The problem was fixed like this:

    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>
      )
    }


  2. You can’t have async components. It’s a React fundamental.

    You could try something like this:

    import React, { useState, useEffect } from "react";
    
    async function loadImg() {
      const res = await fetch("http://localhost:4000/api/getImages");
      const data = await res.json();
      return data;
    }
    
    export default function ImgPage() {
      const [imgs, setImgs] = useState([]);
    
      async function fetchData() {
        const imgData = await loadImg();
        setImgs(imgData);
      }
    
      useEffect(() => {
        fetchData();
      }, []);
    
      return (
        <div>
          {imgs.map((img) => (
            <div key={img._id}>
              <h3>{img.date}</h3>
              <img
                src={"http://localhost:4000/files/" + img.filename}
                alt={img.originalname}
              />
            </div>
          ))}
        </div>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search