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

343
Visualizações
How to pass data from a component into getServerSideProps

I'm having trouble figuring out how to pass data from a component to getServerSideProps, basically what I want is to get the value of text input and use it as a keyword in my API call. The text input will be located in a "SearchBar" component that will be visible on every page of my application and on button click I want to make the API call using the value of the input in a proper page called "SearchResults". What is the best way to do that?

SearchBar:

import { useState } from 'react';

export default function SearchBar() {
  const [keyword, setKeyword] = useState('');

  const handleClick = (event) => {
    event.preventDefault();
    console.log(keyword);
  };
  return (
    <div>
      <input
        type="text"
        value={keyword}
        onChange={(e) => setKeyword(e.target.value)}
      />
      <button onClick={handleClick}>Fetch</button>
    </div>
  );
}

SearchResults:

import { GetServerSideProps } from 'next';

export const getServerSideProps: GetServerSideProps = async (context) => {
  const { keyword } = context;
  const res = await fetch(
    `https://www.googleapis.com/books/v1/volumes?q=${keyword}`
  );
  const data = await res.json();

  return { props: {} };
};

export default function SearchResults() {
  return (
    <div>
      <h1>Teste</h1>
    </div>
  );
}

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

0

i am guessing, that your api call for the textinput will be a client side call, because it needs client interaction on top of it.

So no need to do server side calls.

Just onChange call your api, and it will be done.

import { useState } from 'react';

export default function SearchBar() {
  const [keyword, setKeyword] = useState('');

  const handleClick = (event) => {
    event.preventDefault();
    fetchData(keyword);
  };

  const fetchData = async(keyword) => {
     const res = await fetch(
    `https://www.googleapis.com/books/v1/volumes?q=${keyword}`
  );

  const data = await res.json();
  };


  return (
    <div>
      <input
        type="text"
        value={keyword}
        onChange={(e) => setKeyword(e.target.value)}
      />
      <button onClick={handleClick}>Fetch</button>
    </div>
  );
}

lastly, you can wrap your component with layout, so that your search component will be visible in every page.

// pages/_app.js

import SearchComponent from '../components/SearchComponent'

export default function MyApp({ Component, pageProps }) {
  return (
    <div>
      <SearchComponent/>
      <Component {...pageProps} />
    </div>
  )
}

Refer here for nextjs layouts

about 4 years ago · Juan Pablo Isaza Relatório

0

you wrap the input with form:

<form onSubmit={submitHandler} >
     <input
        type="text"
        value={keyword}
        onChange={(e) => setKeyword(e.target.value)}
      />
</form>

write submitHandler:

const submitHandler = (event) => {
    event.preventDefault();
    if (keyword) {
      Router.push({
        // whatever your baseUrl
        pathname: process.env.BASE_URL,
        query: { keyword: keyword, page: 1 },
      });
    // Optional
    } else if (keyword === "") {
      Router.push({ pathname: "", query: { page: 1 } });
    } else {
      Router.push(Router.router.asPath);
    }
  };

then in getServerSideProps you reach the query the way you wrote the code

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