Pedro Bennesby
Pedro Bennesby

Reputation: 31

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

Upvotes: 2

Views: 1511

Answers (2)

abhikumar22
abhikumar22

Reputation: 1814

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

Upvotes: 3

Yilmaz
Yilmaz

Reputation: 49321

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

Upvotes: 1

Related Questions