View source not displaying dynamic content

后端 未结 3 940
臣服心动
臣服心动 2021-01-25 05:59

I am making very simple next js application, where everything is working fine but except the view source.

I am making a promise and there is a delay in retrieving conten

3条回答
  •  面向向阳花
    2021-01-25 06:50

    You're explicitly telling React to fetch a user on a client-side.

    function Profile() {
      const { data, revalidate } = useSWR("/api/user", fetch);
    }
    

    If you need to prerender a user info on the server you can do it with one of the following functions:

    • getStaticProps (Static Generation): Fetch data at build time
    • getServerSideProps (Server-side Rendering): Fetch data on each request.

    As you fetching a user info, I assume that it should be requested on each request, so use getServerSideProps.

    const URL = 'api/user/'
    
    export default function Profile({ initialData }) {
      const { data } = useSWR(URL, fetcher, { initialData })
    
      return (
        // render 
      )
    }
    
    export async function getServerSideProps() {
      const data = await fetcher(URL)
      return { props: { initialData: data } }
    }
    

    This way you would fetch a user info on the server and give it to React with first render. Also, you would have useSWR on a client side that will periodically revalidate data.

    Suggested reading: Data fetching

提交回复
热议问题