简体   繁体   中英

How to use data picked from GetStaticProps, globally in NextJS/apollo/graphql?

As the title says, I want to use data from GetStaticProps in another file, in another component. Can not use GetStaticProps in the component because:

Server Error Error: getStaticPaths is required for dynamic SSG pages and is missing for '/[title]'.

Basically, I want to use data gathered from GetStaticProps in nextjs dynamic route file. Tried to fix it by myself for several hours, researched but couldn't find a fix. I need help, any suggestions?

Below you will find code from both files and also the picture of my file structure.

Filestructure

index.js:

import s from '../styles/Home.module.css'
import { gql } from "@apollo/client";
import client from '../client/apollo-client';
import Postcard from '../components/Postcard';
import Logo from '../components/Logo';
import React, { useState, useEffect } from 'react';


export default function Home({ cards, WelcomeText, categories }) {

  // Store data in state
  let [data, setData] = useState(cards)


  // Filter start ======================================

  const [searchTerm, setSearchTerm] = useState('');

  // Filter end ========================================

  return (
    <div className={s.mainContainer}>
     
      <Logo/>
      <p className={s.welcomeText}>{WelcomeText.attributes.Text}</p>

      {/* Filter search start =========================== */}
      <div className={s.filterContainer}>
        <div className={s.searchContainer}>
          <p>
            <input className={s.searchFilther} type="text" placeholder="Search for topic..." onChange={event => {setSearchTerm(event.target.value)}} />
          </p>  
          
        </div>
      </div>
      {/* Filter search end =========================== */}

      <div className={s.contentContainer}>
        
        <div className={s.contentLeftColumn}>
        </div>

        <div className={s.contentRightColumn}>        
          {/* Cycle and filther through Postcards ===== Start*/}
          {data.filter((value)=>{
            if(searchTerm == ""){
              return value
            } else if (
              value.attributes.Title.toLowerCase().includes(searchTerm.toLowerCase())){
              return value
            } else if (
              value.attributes.Category_keywords.toLowerCase().includes(searchTerm.toLowerCase())){
              return value
            }
          }).map((card) => (
            <div  key={card.id} className={s.cardContainer}>
              <Postcard
                className={s.postCardContainer}
                clue={card.id}
                title={card.attributes.Title}
                duration={card.attributes.Duration}
                updateDate={card.attributes.updatedAt}
                description={card.attributes.Description}
                guide={card.attributes.UniqueLink === null ? `${card.attributes.Title}` :`${cards.attributes.UniqueLink}` }
                categories={card.attributes.categories.data.map((category)=>(
                            category.attributes.Category+" "))
                }
              />
            </div>
          ))}
          {/* Cycle and filther through Postcards ===== End*/}
          
        </div>
      </div>

    </div>
  )
}

// graphql request for Postcards
export async function getStaticProps() {
  const { data } = await client.query({
    query: gql`
    query PostCards{
      postCards(pagination: { start: 0, limit: 1000 }){
        meta{
          pagination {
            page
            total
            pageSize
            pageCount
          }
        }
        data{
          id
          attributes{
            Title
            Duration
            publishedAt
            updatedAt
            Description
            Category_keywords
            UniqueLink{
              UniqueLink
            }
            Link{
              Link
              Target
            }
             categories{
              data{
                id
                attributes{
                  Category
                }
              }
            }
          } 
        }
      }
    categories{
      data{
        id
        attributes{
          Category
        }
      }
    }
    welcomeText{
      data{
        attributes{
          Text         
        }
      }
    }
    postContents {
      data{
        id
        attributes{
          Title
        }
      }
    }
    }
    `
  })
 

 
// data.postCards.data returns Array of Postcards
// data.welcomeText.data returns just an intro text
  return {
    props: {
      cards: data.postCards.data,
      WelcomeText: data.welcomeText.data,
      categories: data.categories.data,

      // pagination
      totalCount: data.postCards.meta.pagination.total,
      pageCount: data.postCards.meta.pagination.pageCount,
      pageSize: data.postCards.meta.pagination.pageSize,

      // post content
      content: data.postContents.data,

    }
  }
}

[title].js

const PostContent = () => {
    return ( 
        <div>
         
        </div>
     );
}
 
export default PostContent;

From what I understand, you need dynamic pages for every post based on post's title which you are fetching with getStaticProps in index.js .

You should also use getStaticPaths to pre-render the dynamic "titles" path list.

You can read more here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM