Untitled
import React, { useState, useEffect } from 'react'; import Select from 'react-select'; import { useHistory } from 'react-router-dom'; // Importer useHistory de react-router-dom const SearchBar = () => { const [inputValue, setInputValue] = useState(''); const [options, setOptions] = useState([]); const history = useHistory(); // Utiliser le hook useHistory // Fonction pour charger les films depuis l'API const loadOptions = (inputValue) => { fetch(`https://api.themoviedb.org/3/search/movie?include_adult=false&language=en-US&page=1&query=${inputValue}`, { method: 'GET', headers: { accept: 'application/json', Authorization: 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxYzVhOTk4ODVlMTY0MTc1NTM5YWNiYzIwMWE3NjI4NCIsInN1YiI6IjY1ODFhZmIxMGU2NGFmMDgxZWE5MzhmYiIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ._cDptt5s5Nosx6tgjX53sHiyhJzqsdRwkCmZtVq15jM' } }) .then(response => response.json()) .then(response => { const movies = response.results.map(movie => ({ value: movie.id, label: movie.title })); setOptions(movies); }) .catch(err => console.error(err)); }; // Gère le changement dans la barre de recherche const handleInputChange = (newValue) => { const inputValue = newValue.replace(/\W/g, ''); setInputValue(inputValue); return inputValue; }; // Nouvelle fonction pour gérer la sélection d'une option const handleChange = (selectedOption) => { // Redirection vers la page de détails du film history.push(`/details/${selectedOption.value}`); }; useEffect(() => { if (inputValue) { loadOptions(inputValue); } }, [inputValue]); return ( <Select value={inputValue} onInputChange={handleInputChange} onChange={handleChange} // Ajouter le gestionnaire onChange options={options} /> ); }; export default SearchBar;
Leave a Comment