To fetch different data from API should I use different request or one single fetch changing the variable?. I have looked through internet and the answer/suggestion are almost all towards to PHP and I do not know this language really well. Therefore I am here to ask for suggestion/answer.
This is my code so far:
//fetching movie
fetchMovie = (name) =>{
const API = '&api_key=72049b7019c79f226fad8eec6e1ee889';
let movieAPI = '';
//if the length of the movies is equal to zero fetch default search
if( this.state.movies.length === 0 ){
movieAPI = "https://api.themoviedb.org/3/discover/movie?api_key=72049b7019c79f226fad8eec6e1ee889&sort_by=popularity.desc&page=1";
}else{
//search the movie name
movieAPI = "https://api.themoviedb.org/3/search/movie?page=1&query=" + name + API;
}
//make request
const req = new Request(movieAPI, {
method: 'GET',
cache: 'default'
});
fetch(req).then(response =>{
return response.json();
}).then(data =>{
//if data fetched result is greater than 0
if(data.results.length > 0){
this.setState({
movies: data.results
});
}
}).catch(err => {
console.log("ERROR: " + err);
})
}
Now to explain what I want to understand is: As you can see from the code above I can only do a default request data or by name. Now if I want to fetch different query should I write a different code each of the query or reuse the code making so:
movieAPI = "https://api.themoviedb.org/3/"+ variable +"/movie?api_key=72049b7019c79f226fad8eec6e1ee889&date="+ date +"&name=" +name + "&otherQuery=" + query ;
It really depends on what your app will do with these data.
I suggest you to create multiple functions for each type of data your app will fetch like these :
function fetchMovieByName(name){ ... }
function fetchMovieListByDate(beginDate, endDate, sort, page){ ... }
function fetchPopularMovieList(sort, page){ ... }
function fetchTopRatedMovieList(sort, page){ ... }
It'll be cleaner and easier to understand your code.
In case you want to do less requests you can fetch a list then store it and work on it client side to search/filter etc...
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.