I have a component that handles a request for data from our backend. The request is based on what the user clicks on in our UI and sometimes the request returns a bunch of data and sometimes it doesn’t.
We’re seeing an issue where a user will click a large request and then immediately click a small request. The problem is the small request returns before the large request, then the large request returns and overwrites the users last, smaller request.
function handleRequest() {
useEffect(() => {
getTableData();
}, [mainContext?.tableFilterContext])
async function getTableData() {
mainContext?.setTableData({
...mainContext?.tableData,
tableLoading: true
})
let data = await handleTableDataRequest(mainContext?.tableFilterContext);
mainContext?.setTableData({
tableData: data,
tableLoading: false
})
}
}
How can we make sure that the data that is loaded into the mainContext?.tableData
is always the users last requested data?
2
Answers
I fixed this using
AbortController
In this example, Promise.all() is used to execute three fetch requests concurrently. The results are then combined or processed as needed. This ensures that the requests are executed concurrently but the results are handled in the correct order, maintaining the order of the requests.