Stopping a data state being set if the user navigates away from the page

There is a slight problem in the page components at the moment when they request data and set this in the state. The problem is if the user navigates away from the page while the data is still being fetched, the state will attempt to be set on a component that no longer exists. We are going to resolve this issue on the HomePage, QuestionPage, and SearchPage components by carrying out the following steps:

  1. In HomePage.tsx, let's change the useEffect call to the following:
 useEffect(() => {
let cancelled = false;
const doGetUnansweredQuestions = async () => {
const unansweredQuestions = await getUnansweredQuestions();
if (!cancelled) {
setQuestions(unansweredQuestions);
setQuestionsLoading(false);
}
};
doGetUnansweredQuestions();
return () => {
cancelled = true;
};
}, []);

We use a cancelled variable to track whether the user has navigated away from the page and don't set any state if this is true. We know whether the user has navigated away from the page because the return function will be called, which sets the cancelled flag.

  1. Let's follow the same pattern for the QuestionPage component:
useEffect(() => {
let cancelled = false;
const doGetQuestion = async (questionId: number) => {
const foundQuestion = await getQuestion(questionId);
if (!cancelled) {
setQuestion(foundQuestion);
}
};
...
return function cleanUp() {
cancelled = true;
...
};
}, [match.params.questionId]);
  1. Lastly, let's follow the same pattern for the SearchPage component:
useEffect(() => {
let cancelled = false;
const doSearch = async (criteria: string) => {
const foundResults = await searchQuestions(criteria);
if (!cancelled) {
setQuestions(foundResults);
}
};
doSearch(search);
return () => {
cancelled = true;
};
}, [search]);

This completes the changes to the page components. The data fetching process within the page components is now a little more robust.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.131.94.5