skip to Main Content

I want to use an array that is on another page. I need the array information for the title and meta tags, but it seems that in next js it takes time to load the information, so I encounter undefined at first. What solution should I use to load this array?

(I can’t put the array in the same file because I need it in some other pages as well.)

I also tried get static props but it returns undefined as props.
Should I use swr? What is the best solution for seo?

import { items } from "../../public/assets/ArticlesList.js";

const ArticlePage = () => {
  const router = useRouter();
  const { id } = router.query;
  let data = items[id];

  return (
    <>
      <Head>
        <title> {data.title}  </title>
      </Head>
      <div>
        ....
      </div>
   </>
   )
   }

2

Answers


  1. I recommend using getServerSideProps

    import { items } from "../../public/assets/ArticlesList.js";
    
    const ArticlePage = ({ data }) => {
      return (
        <>
          <Head>
            <title> {data.title}  </title>
          </Head>
          <div>
            ....
          </div>
       </>
      );
    }
    
    export async function getServerSideProps(context) {
      const { id } = context.query;
      const data = items[id];
    
      return {
        props: { data }
      }
    }
    
    export default ArticlePage;
    
    Login or Signup to reply.
  2. Make a common component like below: and import on top of the page. Then you won’t have any problem of undefined data.

    import Head from 'next/head';
    
    const MetaData = (props) => {
      const title = props.title || '';
      const description = props.description || '';
      const keywords = props.keywords || '';
      const image = props.image || '';
    
      return (
        <Head>
          <title>{title}</title>
          <meta name="description" content={description} />
          <meta name="og:description" content={description} />
          <meta name="twitter:description" content={description} />
          <meta name="twitter:site" content="" />
          <meta name="twitter:card" content="summary" />
          <meta name="twitter:title" content={title} />
          <meta name="og:site_name" content="" />
          <meta name="og:title" content={title} />
          <meta name="keywords" content={keywords} />
          <meta name="og:image" content={image} />
        </Head>
      );
    };
    
    export default MetaData;
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search