1

So i have Search component and whenever the search get submitted and redirected to a home page with results in it. The problem is that after submission my Search component layout disappears.

import React, { useContext, useEffect } from 'react';
import { MovieContext } from '../context/MovieContext';
import { Redirect } from 'react-router-dom';

const Search = () => {
  const { search, setSearch, setMovies, setAlert } = useContext(MovieContext);

  const searchMovies = async e => {
    e.preventDefault();
    if (search.query === '') {
      setAlert('Please enter something...');
      setTimeout(() => {
        setAlert('');
      }, 5000);
    } else {
      const response = await fetch(
        `https://api.themoviedb.org/3/search/movie?api_key=35f31bc5ec65018dd8090674c49fe3d2&language=en-US&query=${search.query}&include_adult=false`
      );
      const data = await response.json();
      setMovies(data.results);
      setSearch({ query: '', redirect: true });
    }
  };

  const updateSearch = e => {
    setSearch({ query: e.target.value });
  };

  if (search.redirect === true) {
    return <Redirect to='/' />;
  }

  return (
    <form
      className='form-inline justify-content-center w-75'
      onSubmit={searchMovies}
    >
      <input
        className='form-control mr-sm-2 w-50'
        type='text'
        value={search.query}
        placeholder='Search for the movie, person, tv show...'
        onChange={updateSearch}
      />
      <button className='btn btn-outline-light my-2 my-sm-0' type='submit'>
        Search
      </button>
    </form>
  );
};

export default Search;

I know what this happens because i return Redirect and not JSX with my layout. And i struggle to make them both render. I would really appreciate your help.

Before i search anything

After i searched

  • https://stackoverflow.com/questions/52064303/reactjs-pass-props-with-redirect-component – Wen W Mar 03 '20 at 03:31
  • so when you redirect to the home page, add the results as part of it. – Wen W Mar 03 '20 at 03:32
  • I do have results of search. I don't have search component at the top after i searched something... – Alik Krasnorutskiy Mar 03 '20 at 10:20
  • Why do you call this `if (search.redirect === true) { return ; }` ? You should send the results with it or prevent reloading completely. – mw509 Mar 03 '20 at 10:27
  • So when the certain movie is opened and I search for something it will be redirected to a home page with results of search. – Alik Krasnorutskiy Mar 03 '20 at 10:53
  • In that case, then you need to lift your search component above the routes so that you will always have it for all your other components. something like this question here: https://stackoverflow.com/questions/36262360/react-router-global-header – Wen W Mar 03 '20 at 12:11
  • Well i did it but still nothing has changed. After i submit search component disappears... – Alik Krasnorutskiy Mar 03 '20 at 12:45

0 Answers0