rerender is adding fetch results again and again.

issue occurs at setWatchListData. im trying to insert unique objects by comparing the ids. whenever it renders it adds same object inside an array
const fetchWatchList = (list) => {
fetch(`https://api.themoviedb.org/3/movie/${list[0]}?external_source=imdb_id&api_key=${API_KEY}`)
.then(response => response.json())
.then(response => {
setWatchListData(prevlist => {
const isMovieAdded = prevlist.filter(movie => movie.id !== response.id)

if (isMovieAdded.length === 0) {
return [...prevlist, response]
} else {
return prevlist;
}
})
})
.catch(err => console.error(err));
}

useEffect(() => {
watchList?.map((list) => (
fetchWatchList(list)))
}, [watchList])
const fetchWatchList = (list) => {
fetch(`https://api.themoviedb.org/3/movie/${list[0]}?external_source=imdb_id&api_key=${API_KEY}`)
.then(response => response.json())
.then(response => {
setWatchListData(prevlist => {
const isMovieAdded = prevlist.filter(movie => movie.id !== response.id)

if (isMovieAdded.length === 0) {
return [...prevlist, response]
} else {
return prevlist;
}
})
})
.catch(err => console.error(err));
}

useEffect(() => {
watchList?.map((list) => (
fetchWatchList(list)))
}, [watchList])
2 Replies
Joao
Joaoā€¢17mo ago
Because your fetch call happens at the component level. You should include that within the useEffect hook.
Avinash
Avinashā€¢17mo ago
useEffect(() => {
watchList?.map((list) => (
fetchWatchList(list)))
}, [watchList])
useEffect(() => {
watchList?.map((list) => (
fetchWatchList(list)))
}, [watchList])
this one will only trigger if ther is change in watchlist šŸ¤”
Want results from more Discord servers?
Add your server