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

110
Visualizações
Manipulating server side API with state value

So I built an app in React but later switched to Next.js as my api provider only accepted api calls in the server side, I had built a pagination in react very easily using useState and template literals however, I'm kind of confused how I would do the same when API calls are being made on the server side instead.

My server side fetch code is simple and looks like this -

export async function getStaticProps() {
    try {
        const result = await fetch(`https://exampleapi.com/running?sort=&page={$page_no}&per_page=30&#`);
        const data = await result.json();

        return {
            props: { game: data },
           
        };
    } catch (error) {
        res.statusCode = 404;
        return { props: {} };
    }
}


const BoxScore = () => {
  const [page_no, setPage_no] = useState(1);

  const incrementPageNumber = () => {
    setPage_no((page_no) => page_no + 1);
    console.log(page_no);
  };

  const decrementPageNumber = () => {
    if (page_no <= 1) return;
    setPage_no((page_no) => page_no - 1);
  };

 return (
       <div className="container">
        <div className="ctrl-div">
          <button className="ctrl-butts" onClick={incrementPageNumber} >Next</button>
          <button className="ctrl-butts" onClick={decrementPageNumber}> Previous</button>
  
        </div>
  
            <div className="container">
                <h2>Live Games  - </h2>
                <div className="columns is-multiline">
                {game.map(q => (
         <div className="column is-half" key={q.id}>
                <div className="inner">
               {q.name}
</div>
</div>
  
           

So I want to pass the {page_no} into the api request I'm making so my pages can change dynamically, I know I cannot pass the state values into getStaticProps as mentioned in the docs but as I'm restricted to SSR data fetching only, I'm not sure how to go about with this. Any ideas or resources to tackle this would be very appreciated

Edit - For clarification I've added more code, basically - I'm trying to paginate the data I receive from the API and the API has pagination endpoint so this makes it a little easier, I just am not sure how I would pass the value of my {page_no} into the getStaticProps method.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You should fetch dynamic data in getStaticProps because it is run only during build time. (exeption is incremental-static-regeneration but wont work in your case) You need to use getServerSideProps and read the query params. serverside functions in next.js accepts context argument.

export async function getServerSideProps(context) {
    // console.log(context)
    try {
        const { query } = context;
        // since query is an obj, you can add properties withoud defining as let keyword above
        if (!query.page) {
           query.page = "1";
        }

        const result = await fetch(`https://exampleapi.com/running?sort=&page=${query.page}&per_page=30&#`);
        const data = await result.json();

        return {
            props: { game: data },          
            
        };
    } catch (error) {
        res.statusCode = 404;
        return { props: {} };
    }
}
about 4 years ago · Santiago Trujillo 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