Home > Mobile >  React-TypeScript API Search functionality not working
React-TypeScript API Search functionality not working

Time:06-06

We're trying to add a search function in our class project, but aren't getting any results. If we type in the input, then go back to the code and save it, then it will work. But the onSubmit isn't working on it.

Here is the Search component

import React, { useEffect, useState } from 'react'
import SearchMovieResults from '../models/Search';
import GetMovies from '../services/GetMovie';

function Search() {
  const [search, setSearch] = useState<string>("");
  const [title, setTitle] = useState<string>("");
  const [movie, setMovie] = useState<SearchMovieResults[]>([])
  useEffect(() => {
    GetMovies(title).then(data => {
        setMovie(data);
    });
  }, []);
  return (
    <div>
      <form onSubmit={(e) => {
        e.preventDefault();
        setTitle(search);
        console.log(title);
        }}>
        <label htmlFor="search">SEARCH:</label>
        <input type="text" name="" id="search" placeholder="Type movie/tv show here" onChange={(e) => {setSearch(e.target.value)}}/>
        <button type="submit">SEARCH</button>
    </form>
    {movie.map((title, index) =>
      <p key={index}>{title.title}</p>
    )}
    </div>
  )
}

export default Search;

And here is the API we used.

import axios from "axios";
import Movie from "../models/MovieInterface";
import SearchMovieResults, { SearchMovie } from "../models/Search";

export default function GetMovies(search: string) : Promise<SearchMovieResults[]> {
    return axios
        .get<SearchMovie>(`https://api.themoviedb.org/3/search/movie?api_key={api-key}&query=${search}`)
        .then((response) => {return response.data.results})
}

And here is the interface.

export interface SearchMovie{
    results: SearchMovieResults[]
}

export default interface SearchMovieResults{
    genres_ids : number[],
    backdrop_path : string | null,
    title : string,
    overview : string,
    vote_average : number,
    poster_path : string,
    release_date : string,
    runtime : number
}

ANY input would be greatly appreciated, Thanks!

CodePudding user response:

If you want to look for movies everytime that the form is submitted, then add title to your dependecy array:

useEffect(() => {
    GetMovies(title).then(data => {
        setMovie(data);
    });
  }, [title]);

then the useEffect will be executed everytime that title changes, and this happens whenever the form is submitted

  • Related