Reputation: 91
I'm fetching from the moviedb api and working on searching movies. I've taken some reference from alligator.io tutorial. Below is my code of the Header component where i am fetching the data.
Header.js
import React, { Component } from "react"
import { Navbar, Button, Form, FormControl } from "react-bootstrap"
import { NavLink } from "react-router-dom"
import axios from "axios"
const apiKey = process.env.REACT_APP_MOVIE_DB_API_KEY
class Header extends Component {
state = {
isSearching: false,
value: "",
movies: []
}
searchMovies = async val => {
console.log("val", val)
this.setState({ isSearching: true })
const res = await axios(
`https://api.themoviedb.org/3/search/movie?api_key=${apiKey}&language=en-US&query=${val}page=1&include_adult=true`
)
const movies = await res.data.results
console.log(movies)
this.setState({ movies: movies, isSearching: false })
}
handleChange = e => {
const { name, value } = e.target
this.searchMovies(value)
this.setState({
[name]: value
})
}
handleSearch = () => {
console.log(this.state.movies)
}
render() {
return (
<div>
<Navbar
bg="dark"
expand="lg"
style={{ justifyContent: "space-around" }}
>
<NavLink to="/">
<Navbar.Brand>Movie Catalogue</Navbar.Brand>
</NavLink>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Form inline>
<FormControl
type="text"
placeholder="Search"
className="mr-sm-2"
onChange={this.handleChange}
name="value"
value={this.state.value}
/>
<Button variant="dark" onClick={this.handleSearch}>Search</Button>
</Form>
</Navbar.Collapse>
<NavLink to="/popular">Popular</NavLink>
<NavLink to="/now-playing">Now Playing</NavLink>
<NavLink to="/top-rated">Top Rated</NavLink>
<NavLink to="/upcoming">Upcoming</NavLink>
</Navbar>
</div>
)
}
}
export default Header
I am getting an empty array in movies
. When I console log this.state.movies
inside handleSearch
it's stil returning an empty array. I don't know why's it happening. The url and everything is correct but I'm getting an empty array.
Upvotes: 0
Views: 596
Reputation: 9652
You are not calling appropriate method of axios. Use get() method
Try this:
searchMovies = async val => {
this.setState({ isSearching: true })
const res = await axios.get(
`https://api.themoviedb.org/3/search/movie?api_key=${apiKey}&language=en-US&query=${val}page=1&include_adult=true`;
)
const movies = await res.data.results;
this.setState({ movies: movies, isSearching: false })
}
Upvotes: 0
Reputation: 56
I think you should use get() method in your searchMovies function.
const response = await axios.get('/user?ID=12345');
console.log(response);
Upvotes: 1