Luca Lago
Luca Lago

Reputation: 35

Execute GetServerSideProps each time i click on a button

I've been creating an app with NextJS, my problem came when I tried to generate new content from an API when I click on a button. I get the server call succesfully but it gets updated only when I reload the page, not when I click on the button as I want. Here's the code:

import React, {useState} from 'react'
import { FaCog } from 'react-icons/fa'

export async function getServerSideProps() {
    const res = await fetch(`https://animechan.vercel.app/api/random`)
    const data = await res.json()
  
    return {
      props: {
        quote: data.quote,
        anime: data.anime,
        character: data.character
      }
    }
  }

const Button = () => {
  
    const [clicked, setClicked] = useState(false)

    const handleClicked = (props) => {
        return (
            <div>
                <p style={{fontWeight: 'bold'}}>{props.anime}</p>
                <p>{props.quote}</p>
                <p style={{fontWeight: 'bold'}}>-{props.character}</p>
            </div>
        )
        setClicked(!clicked)
    }

    return (
    <div className="main_button">
        <button onClick={handleClicked}>{clicked ? 'Generate again...' : 'Generate content '} <FaCog className={clicked ? 'main_button-spinner' : null}/> </button>
    </div>
  )
}

export default Button

I want that each time I click on the button, the content gets updated and I receive new content from the API. As I explained above, this is working fine on the API call, but the content gets updated just by reloading the page and not as I need it to work. Any idea?

Upvotes: 0

Views: 4125

Answers (1)

Shea Hunter Belsky
Shea Hunter Belsky

Reputation: 3238

You're misunderstanding the role of getServerSideProps. Take a look at the Next.js documentation: https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props

getServerSideProps only runs on server-side and never runs on the browser

If you want your React application to change in response to hitting this API, then you need to submit a request to the API from within the React code (in response to the button click), save the results of the API to state, and then display the results in the frontend.

Psuedo code follows:

const [data, setData] = useState(null);
// ...
async function handleClicked() {
  const apiResponse = await fetch("...");
  setData(apiResponse); // Or whatever properties from the response you care about
}
// ...
<button onClick={handleClicked}>
  {clicked ? 'Generate again...' : 'Generate content '}
  <FaCog className={clicked ? 'main_button-spinner' : null}/>
</button>

Upvotes: 4

Related Questions