skip to Main Content

I’m trying to re-write a project previously done in React with nextjs. I have a simple page that uses getStaticProps along it with its required ally, getStaticPaths. The issue is that the returned data (object) is available if I console log it, but doesn’t show on the page jsx. I have done everything I know to do to no avail.
The getStaticProps and getStaticpaths are as follows:

export async function getStaticProps(context) {
    try {
    const slug = context.params.slug;
    const response = await fetch(`http://127.0.0.1:8000/api/product/${slug}/`);
    const data = await response.json();
    return {
        props: { product: data },
      };
    } catch (error) {
      console.log(error)  
    }
  }



export const getStaticPaths = async () => {
    try {
    const response =  await fetch(`http://127.0.0.1:8000/api/product/list/`);
    const data = await response.json();
    const allSlugs = data.map(item => item.slug)
    const paths= allSlugs.map(slug => ({params:{slug:slug}}))
    return {
        paths,
        fallback: false,
    }
    } catch (error) {
     console.log(error)   
    }
  }

The page jsx is:

function Product({product}){
    console.log(product) // This displays the product quite alright on the console
return <div>
The following did not work (blank), and no error message
    <h2>{product.name}</h2>
    <p> {product.price}</p>
</div>
}
export default Affidavit

As I said, nothing got displayed on the page, yet there is no error whatsoever. But surprisingly the returned object displays on the console. Please, any idea what could be the issue here

2

Answers


  1. Could you try this instead:

    export async function getStaticProps(context) {
        try {
        const slug = context.params.slug;
        const response = await fetch(`http://127.0.0.1:8000/api/product/${slug}/`);
        const product = await response.json();
        return {
            props: { product },
          };
        } catch (error) {
          console.log(error)  
        }
      }
    
    Login or Signup to reply.
  2. You should return your html in your product component within ().

    Your code would look like this:

    function Product({product}){
        console.log(product) // This displays the product quite alright on the console
    return (
      <div>
        The following did not work (blank), and no error message
        <h2>{product.name}</h2>
        <p> {product.price}</p>
      </div>
    )}
    export default Affidavit

    If this fails, please share your console.log() output.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search