Ad

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

Ad

Answer

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

Ad
source: stackoverflow.com
Ad