SetTimout in react export function

Viewed 47

What is the right way to add setTimeout in this function? Next js WP headless CMS

export async function getStaticProps() {
      const allPosts = await getAllPosts();
      return {
        props: {
          allPosts
        }
      };
    }
2 Answers

This might get what you want

export async function getStaticProps() {
    return setTimeout( async () => {

        // executes this block of code after the timeout(2 seconds)
        const allPosts = await getAllPosts();
        return {
            props: {
                allPosts
            }
        };
    }, 2000) //2 seconds (2 * 1000)
}

You can try something like

export async function getStaticProps() {
   return new Promise((res, rej) => {
      setTimeout(async () => {
        const allPosts = await getAllPosts();
        res({ props: { allPosts } })
       }, 2000)
   })
}

Basically returning a promise that will be resolved after 2 seconds. This way you can use await getStaticProps() in other functions.

Related