julBayonna
julBayonna

Reputation: 449

how can I refetch with getServerSideProps in next on a click on client side?

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 from the API call, the page does not refresh... Even thought I am using useState which should force the page to refresh.

Upvotes: 0

Views: 2548

Answers (2)

ivanatias
ivanatias

Reputation: 4033

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.

Upvotes: 2

julBayonna
julBayonna

Reputation: 449

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>
  )

Upvotes: 0

Related Questions