Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

266
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda