In my app I have 3 components:
MovieSearchComponentto "house" the other 2 componentsMovieSearchto search an API and retrieve the dataMovieResultListto display the data in the browser
Both components are wrapped in a parent container MovieSearchComponent.
My MovieSearchComponent looks like this:
interface Movie {
original_title: string;
id: string;
}
const MovieSearchComponent = () => {
const [movieList, setMovies] = useState<Movie[]>([]);
const addMovie = ((movies: Movie[]) => {
setMovies([...movies]);
});
return (
<React.Fragment>
<MovieSearch addMovie={addMovie} />
<MovieResultList movieList={movieList}/>
</React.Fragment>
)
}
In here I have a empty MovieList array that uses the setMovies function to fill the MovieList array. There's also a addMovie function that gets called from the MovieSearch component and takes a array as a parameter. Then I pass the MovieList array to the MovieResultList component.
The MovieSearch component:
const Search = styled.input`
color: green;
`
const MovieSearch = ( {addMovie }) => {
const apikey = 'api_key=***************dad4';
const baseurl = 'https://api.themoviedb.org/3/search/movie?'
const searchTMDBapi = (e) => {
e.persist()
setMovieSearchResults(e);
}
const setMovieSearchResults = debounce((e) => {
const query = e.target.value;
fetch(baseurl + apikey + '&language=en-US&query=' + query + '&page=1&include_adult=false')
.then(response => response.json())
.then(data => addMovie(data.results))
}, 500);
return <Search placeholder="Search" onChange={searchTMDBapi}/>
}
In this function component I render a input field by using styled components. The input field calls the searchTMDBapi function when something is typed. In that method I call the setMovieSearchResults method which calls the api and sets the api data in the Hook by using .then(data => addMovie(data.results))
The addMovie Hook updates the movieList array in MovieSearchComponent and the <MovieResultList movieList={movieList}/> syntax passes the movieList array to the MovieResultList which renders it:
const MovieResultList = (props) => {
return (
<div>
<ul>
{props.movieList.map(movie => {
return (<li key={movie.id}>{movie.original_title}</li>)
})}
</ul>
</div>
)
}
My goal was to create 2 components. 1 to retrieve data from a external API and the other to display that data in a different component. I succeeded in that but I was wondering if there are some aspects on which I could improve this code and my React knowledge.