I'm working on a React project that includes a dropdown menu of films to choose from. When I select a film it calls the function filmSelected:
const [selectedFilm, setSelectedFilm] = useState({})
const fetchCharacters = async (l, f) => {
// loops through list (l) and fetches character info from api
let c = 0;
let characters = [];
for (let i = 0; i < l.length; i++) {
try {
const charFetch = await fetch(l[i]);
const response = await charFetch.json();
characters.push(response);
c++;
setCount(c);
} catch (e) {
return e;
}
}
return characters;
};
const filmSelected = async (film) => {
// sets the selected film state to the film selected in dropdown menu
// fetches character info from api
setSelectedFilm(film)
const c = await fetchCharacters(film.characters, film);
setCharacters(c);
};
If I were to select a different film before the for loop completes, it creates a problem and almost seems like the function's for loop is being executed simultaneously with the new call. I'm trying to figure out a way to exit the for loop if the film changes before the for loop has been fully executed.
I'm using useState and setting the selectedFilm state within the function, but it doesn't set the state it fast enough to check if the film passed through the fetchCharacters function and the state of selectedFilm are the same.
Any suggestions would be greatly appreciated. Thank you in advance!
Kevin