There are two pages - the main one with a list of elements and a page with a detailed description of the element. Used react-router.
<Switch>
<Route exact path="/" component={PokemonCardContainer} />
<Route path="/pokemon/:pokemonName" component={Pokemon} />
</Switch>
On the main page with the list, a request api is generated, which returns 20 elements. Further, when we reach the end of the list, the api request is updated - another 20 items are loaded, etc.
The detailed description page is implemented by the button "I Choose You!"
<Link to={`pokemon/${pokemonName}`}>
{pokemonName}, I Choose You!
</Link>
On the detailed description page there is a button "Return to Home"
const handleGoToHomePage = () => {
props.history.push({
pathname: "/",
});
};
Accordingly, when I press return to the main page, a new api request occurs and I get to the top of the page. but I need me to return to the element of the list I clicked on. For example, if I clicked on the 60th element, I need to return to it. I understand that I need to interrupt the api request when I return to the main?
/* States */
const [pokemons, setPokemons] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
const [currentPage, setCurrentPage] = useState(
"https://pokeapi.co/api/v2/pokemon"
);
const [nextPage, setNextPage] = useState("");
const [hasMore, setHasMore] = useState(false);
useEffect(() => {
let cancel;
const fetchData = () => {
setLoading(true);
setError(false);
Axios({
method: "GET",
url: currentPage,
cancelToken: new Axios.CancelToken((c) => (cancel = c)),
})
.then((res) => {
setPokemons((prevPokemons) => {
return [...prevPokemons, ...res.data.results];
});
setNextPage(res.data.next);
setHasMore(res.data.results.length > 0);
setLoading(false);
})
.catch((error) => {
if (Axios.isCancel(error)) return;
setError(true);
});
};
fetchData();
return () => cancel();
}, [currentPage]);