Featured

How to write a typescript version of getStaticProps in nextjs taking data from sanity CMS

Posted: December 26, 2022
 export default function getInitials(title: string) {
  // Check if the string is empty
  if (!title) {
    return '';
  }

  // Split the string into an array of words
  let words = title.split(' ');

  // Initialize an empty string to store the initials
  let initials = '';

  // Loop through the array of words
  for (let i = 0; i < words.length; i++) {
    // Get the first character of the current word
    let initial = words[i][0];

    // Convert the character to uppercase
    initial = initial.toUpperCase();

    // Add the character to the initials string, separated by a dot
    initials += initial + '.';
  }

  // Remove the last dot from the initials string
  initials = initials.slice(0, -1);

  return initials;
}

taticProps } from'next'; import sanityClient from'@sanity/client'; // or however you import the Sanity client in your project// Define a TypeScript interface for the props that will be returned by getStaticPropsinterfaceProps { // Repla

ce this with the actual shape of the data you want to fetch from Sanitytitle: string; description: string; } // The function that will be called to retrieve the propsexportconstgetStaticProps: GetStaticProps<Props> = async () => { // Create an instance of the Sanity clientconst client = sanityClient({ projectId: 'your-project-id', dataset: 'your-dataset-name', token: 'your-api-token', useCdn: true, // optional, but can improve performance if your

dataset is public }); // Use the client to fetch the data you need from the Sanity CMSconst data = await client.fetch( `*[_type == "page" && slug.current == $slug][0]`, { slug: 'home' } // replace this with the actual slug of the page you want to fetch ); // Return the data as propsreturn { props: { title: data.title, description: data.description, }, }; };

Writer: Rocky Essel

Reference

8 1421:09 PM

Category

Web DevelopmentNextJS

Share Post

MongoDB BlogMongoDB BlogProject 05+
8 comment
MongoDB Blog
Dec 30, 2022 9:40 AM

the boyu

MongoDB Blog
Dec 30, 2022 11:13 AM

should get 5

Project 0
Dec 30, 2022 9:38 AM

good website

Project 0
Dec 30, 2022 11:07 AM

just added the 5th comment

ROCKY ESSEL
Dec 30, 2022 11:09 AM

you are my friend for life

Project 0
Dec 30, 2022 11:11 AM

i should get 4

Rocky Essel
Dec 30, 2022 9:16 AM

this is a really nice website that you've built?

Rocky Essel
Dec 30, 2022 9:41 AM

df

  • Made With