I am making a react-native app, I am fetching a list of movies from an API, and every time I press next I'm to supposed to get fetch the next list of movies, however, my code doesn't work correctly.
At first, you have to click on the button to fetch the first list like this:
<Button mode="contained" onPress={() => getMovieList()}>
Get Movies
</Button>
const getMovieList= async () => {
setLoading(true);
await fetchMovies(url)
.then(async (data) => {
setData(data);
// more code
})
.catch((error) => {
console.log(error);
});
};
The URL is:
const url = `https://api.themoviedb.org/4/list/${listID}?page=1&api_key=${api_key}`;
I have written a function that I can use to fetch the list using the URL above,
const [listID, setListID] = useState(1);
After I fetch the first list I show them in a child component, like this:
<MyCompanyCard
name={data.companyName}
desc={data.desc}
loadNextCompany={loadNextCompany}
loadPrevCompany={loadPrevCompany}
setListID={setListID}
listID={listID}
/>
And also:
const loadNextCompany = async () => {
setListID(listID 1);
await getMovieCompany();
};
const loadPrevCompany = async () => {
setListID(listID - 1);
await getMovieCompany();
};
In my child component, I call the getNextOne
function and the problem is, although the URL changes but the content doesn't change and I have to press next, then I can see the next list and so on, the same applies for the getPrevOne
. The problem is that every time I press next/prev I make an API call but I am not sure how to set the content to change accordingly.
=================
I was able to solve it by adding a useeffet like this:
useEffect(async () => {
await getMovieCompany();
}, [listID]);
so now every time I add to listID then I fetch the url again and immdedialtly represnt the current items.
CodePudding user response:
try this
const getMovieList = useCallback(() => {
const url = `https://api.themoviedb.org/4/list/${listID}?page=1&api_key=${api_key}`;
setLoading(true);
await fetchMovies(url)
.then(async (data) => {
setData(data);
// more code
})
.catch((error) => {
console.log(error);
});
}, [listID]);
CodePudding user response:
I was able to solve it by adding a useeffet like this:
useEffect(async () => {
await getMovieCompany();
}, [listID]);
so now every time I add to listID then I fetch the url again and immdedialtly represnt the current items.