0

I'm trying to use a fake api found at https://fakestoreapi.com/ to get data into my Next js app. But I keep getting an undefined reference error, even though I got the code snippet from the official next js docs. This is my code

import { Box, Heading } from "@chakra-ui/react";

export async function getStaticProps() {
  const response = await fetch("https://fakestoreapi.com/products");
  const data = await response.json();

  return {
    props: {
      products,
    },
  };
}

function ProductList() {
  return (
    <Box>
      {products.map((product) => (
        <Box>
          <Text> {product.title} </Text>
        </Box>
      ))}
    </Box>
  );
}

export default ProductList;

And this is the error I keep getting

ReferenceError: products is not defined
2
  • "even though I got the code snippet from the official next js docs" - but not for that exact kind of data structure, right ...? Commented Jun 20, 2022 at 10:33
  • No not exactly the same. But it should work either way Commented Jun 20, 2022 at 10:37

1 Answer 1

1

try this:

function ProductList({products}) {
  return (
    <Box>
      {products.map((product) => (
        <Box>
          <Text> {product.title} </Text>
        </Box>
      ))}
    </Box>
  );
}
Sign up to request clarification or add additional context in comments.

7 Comments

I did. Now I get this error TypeError: Cannot read properties of undefined (reading 'map')
rename the data variable to products
I still get the same error
Can you console.log(data) and see what is output, also console response
I commented out the product.map part and console.log the data. It didn't return anything
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.