search query does not display necessary data

Viewed 35

I need to fetch data from API according to search query. As soon as you enter the name of film you are lookng for, you press enter ( submit form) and these films are displayed on the screen. But my console complains. IDK why. I try to implement this using axios and endpoint ${searchText}

function App() {
  const [films, setFilms] = useState([])
  const [searchText, setSearchText] = useState('')

  const url = `http://www.omdbapi.com/?apikey=YOUR_KEY&s=${searchText}`
  useEffect (()=> { 
    loadData()
  }, [])

   const loadData = async () => {
    const res = await axios.get(url)
    setFilms(res.data.Search)
    console.log(res.data.Search)
   }

   const onTextChange = (e) => {
     setSearchText(e.target.value)
   }
   const onSubmitHandler = (e) => {
     e.preventDafault()
     loadData()
  
  }

  return (
    <>
        <Container>
            <h1>Bookstore</h1>
            <Row>
            <form onSubmit={onSubmitHandler}>
            <input type='text'
                   placeholder='Search...'
                   name="searchText"
                   onChange={onTextChange}
                   value={searchText}
                 
            />
            
               </form>
            </Row>
            <Row>
              { films.map(item => {
                return ( 
                
                  <Col lg={3} md={3} sm={12} key={item.imdbID}>
                   <img src={item.poster}/> 
                   <h6>{item.title}</h6>
                   <h6>{item.year}</h6>
                  </Col>

                )
              })}
        
            </Row>
        </Container>
      
    </>
  );
}

Also it complains that films.map is not a function.

1 Answers

key and url update

The "YOUR_KEY" string in the url should be unique string (like: RN33mfknds5josd) then you can update the url with the search text.

const baseUrl = "http://www.omdbapi.com/?apikey=YOUR_KEY" // todo: update the api key

function App() {
  const [films, setFilms] = useState([])
  const [searchText, setSearchText] = useState(baseUrl)

  useEffect (()=> { 
    loadData()
  }, [])

   const loadData = async () => {
    const res = await axios.get(url)
    setFilms(res.data.Search)
    console.log(res.data.Search)
   }

   const onTextChange = (e) => {
     if(e.target.value) {
       setSearchText(`${baseUrl}&s=${e.target.value}`)
     } else {
       setSearchText(baseUrl)
     }
   }
   const onSubmitHandler = (e) => {
     e.preventDafault()
     loadData()
  
  }

  return ...
Related