Home > Blockchain >  how do I properly map a list of images returned using getStaticProps ? inside the same component
how do I properly map a list of images returned using getStaticProps ? inside the same component

Time:10-09

how do i properly map a list of images returned using getStaticProps ?

I had it working when i was using the component i another page and passing a prop to the gallery component. But i want to keep all getstatic props code inside the gallery component.

i keep getting the error enter image description here

here is the component code

import galleryStyles from "../styles/Gallery.module.css";
import { Grid, IconButton } from "@mui/material";
import NavigateNextIcon from "@mui/icons-material/NavigateNext";
import NavigateBeforeIcon from "@mui/icons-material/NavigateBefore";

const Gallery = ({ images }) => {
  return (
    <>
      <Grid className={galleryStyles.container}>
        <div className={galleryStyles.carousel}>
          <IconButton className={galleryStyles.previous}>
            <NavigateBeforeIcon />
          </IconButton>
          <IconButton className={galleryStyles.next}>
            <NavigateNextIcon />
          </IconButton>

          <ul>
            {images.map((image) => (
              <li>
                <img key={image.id} src={image.url} />
              </li>
            ))}
          </ul>
        </div>
      </Grid>
    </>
  );
};

export default Gallery;

export const getStaticProps = async () => {
  const res = await fetch(
    "https://jsonplaceholder.typicode.com/photos?_limit=10"
  );
  const images = await res.json();

  return {
    props: {
      images,
    },
  };
};

CodePudding user response:

Try adding the array to state using useEffect like so

const [imagesArray, setImagesArray] = useState([]);

useEffect(() => {
setImagesArray(prev => [...prev, ...images])
}, [images]);

Then loop with imagesArray.map()

CodePudding user response:

You can't use getStaticProps outside of a next page component (NextPage in TypeScript). That means you can't use getStaticProps in a component which is not inside the /pages subfolder.

getStaticProps is a Server-Side-Rendering feature which is only executed when the page is loaded (not exactly, but simplified). You can't use this anywhere and anytime in your components.

In your code, getStaticProps is not event executed, that is why the images array in undefined.

More information in the Next.js documentation

  • Related