Home > Back-end >  how can i refetch with getServerSideProps in next on a click on client side?
how can i refetch with getServerSideProps in next on a click on client side?

Time:07-09

i am using next.js , and trying to refresh the page with SSR data on a click of a button, doing like so :

import type { NextPage } from 'next'
import { useState } from 'react'

type HomeProps = NextPage & {
  data: any
}

const Home = ({data}: HomeProps) => {
  const [index, setIndex] = useState(data)

  const handleClick = async() => {
    const res = await fetch(`https://fakerapi.it/api/v1/companies?_quantity=2`)
    const data= await res.json()
    setIndex(data)
  }

  return (
    <div>
      {data.data.map(el => (
        <div key={el.id}>{el.name}</div>
      ))}
      <button onClick={handleClick}>next</button>
    </div>
  )
}

export async function getServerSideProps(){
  const res = await fetch(`https://fakerapi.it/api/v1/companies?_quantity=1`)
  const data= await res.json()
  return{ props:{data}}
}

export default Home

I am getting the result of the first api call when next renders the page the first time, but when i click on the button, even though i am getting the result fromt the api call, the page does not refresh...Even thought i am using useState wich should force the page to refresh..

CodePudding user response:

oops my bad, i was not printing out the result of the useState, here is the proper change in the return of the function :

  return (
    <div>
      {index.data.map(el => (
        <div key={el.id}>{el.name}</div>
      ))}
      <button onClick={handleClick}>next</button>
    </div>
  )

CodePudding user response:

Because of the way getServerSideProps works, you could refresh the data on the client-side using router object.

For example, when you click your button it could call a function to programmatically navigate to that same page using: router.replace(router.asPath).

This works because since getServerSideProps runs on every request, and you're already on the client-side and doing a navigation to a SSR page, instead of generating an HTML file, it will send the data as JSON to the client.

This is not a very good solution UX wise tho, but if used correctly it can be very handy.

  • Related