So I am trying to fetch data from this https://fakestoreapi.com/products api but I don't seem to get the results. I don't know whether my procedure is wrong or I am missing something. I am using next.js on top of react with typescript. Kindly assist me. Below is my code to fetch the data.
import React from 'react'
interface Props {
products: {
id: number
title: string
price: string
category: string
description: string
image: string
}[]
}
export const getStaticProps = async () => {
const response = await fetch("https://fakestoreapi.com/products")
const jsonResponse = await response.json()
console.log(jsonResponse);
return {
props: { products: jsonResponse }
}
}
const FetchProducts = ({ products }: Props) => {
return (
<div>
<h1>fetchProducts</h1>
{products.map(product => (
<div key={product.id}>
{product.title}
</div>
))}
</div>
)
}
export default FetchProducts
It doesn't look like you are calling your function getStaticProps, unless it is done in code that isn't shown here.
It seems like you should call it in FetchProducts within a useEffect.
const FetchProducts = ({ products }: Props) => {
useEffect(() => {
const f = async () => {
const p = await getStaticProps()
// do something with p
}
f();
}, []);
return (
<div>
<h1>fetchProducts</h1>
{products.map(product => (
<div key={product.id}>
{product.title}
</div>
))}
</div>
)
}
The name of your component is a little confusing because it is called FetchProducts, but it doesn't fetch anything and instead expects products to be passed in as a prop.
You may want to reconsider how FetchProducts receives products. Should the products be passed in as a prop, or should FetchProducts make a request when the component renders to fetch products? The example above would fetch the products when the component renders which means you would not need a prop for products.