I am stuck in trying to get page 2 results in the same state... Please take a look at my code and help me.
const URL = 'https://api.themoviedb.org/3/movie/now_playing?api_key=#&language=en-US&page=1';
const [movies, setMovies] = useState([]);
const testapi = async() => {
const response = await fetch(urlGiven);
const data = await response.json();
setMovies(data.results);
}
Now I am trying to another request to the api with &page=2 and set that data to append my current movies const... I tried doing setState([...movies, data.results]) again for:
https://api.themoviedb.org/3/movie/now_playing?api_key=#&language=en-US&page=2
PAGE 2 data but that did not render correctly in react native flatlist.
For example, like this:
const secondCALL = async() => {
const response = await fetch(page2URL);
const data = await response.json();
setMovies([...movies, data.results]);
}
How do I go on about appending page 2 data right after page one's original that is set in here: setMovies(data.results);
My flatlist set up, for example ( only showing the relevant part)
<FlatList
data={movies}
/>
You need to add... at data.results, otherwise you will have [movie1, movie2, [movie3, movi4]]
const secondCALL = async() => {
const response = await fetch(page2URL);
const data = await response.json();
setMovies([...movies, ...data.results]);
}
You need to use the spread operator synthax to expands the content of data.results.
consider this example:
const [movies, setMovies] = useState([]);
const [page, setPage] = useState(1);
const getMovies = async () => {
try{
let req = await fetch(`'https://api.themoviedb.org/3/movie/now_playing?api_key=#&language=en-US&page=${page}`);
let data = await req.json();
// spread the content of movies and data
setMovies([...movies, ...data]);
}catch(err){
throw err
}
}
return (...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.