The LOADING… Challenge
Interesting and omni present problem to solve is how to we know that API call you have started is successful, or, failed… just completed. Not only we need to know, we need to inform the user view that data is available.
Various Ajax models requests usually provide ways to go down the path of,
- SUCCESS, when the data you are requesting is available
- FAILURE, when the data you requested returned with an error
- COMPLETE, when the request either succeed or failed so that you can do housekeeping.
A typical tutorial and material available online will tell you that the request you have made will have corresponding variable to store a state to say the request succeeded. Scaling this variable is not relatable, that is which request succeeded it may not tell.
In failure case it becomes more interesting as not only the data has not loaded but you need to present the user with that information.
As we work with multiple Ajax calls, mapping success or failure is a typical problem.
The problem statement is,
- We need an indicator that an Ajax call is in progress
- On success we should be able to change the loading state
- On failure we should be able to change the state and show meaningful message for user
After working through several permutation and combinations of get it right, something that worked for me and is uniquely qualify as a solution is keeping the state and data closer.
Lets create a schema, how we should store the data state on client.
We create our state as,
const state = { personData: { data: {}, loading: false } }
Asynchronous calls take time.
Let us say, function call getPersonData(), returns data object for a person.
On initiation, before a call is initiated, set
state = Object.assign(state, { personData: state.personData, loading: true })
On success, set the loading value to false, set
state = Object.assign(state, { personData: { …state.personData, data: <RETURNED-DATA>, loading: false })
On failure, set the loading value to false, set
state = Object.assign(state, { personData: { …state.personData, loading: false })
VIEW, on data parsing, all developer need to do is to look for loading key of the state. It will provide you the exact state of the data. The exact state will provide a consistent Ajax state of the data you are working with.
To extend it further we can include two other properties,
- error, to store the error returned on failure. Use error: ‘’ on call initiation.
- lastUpdateTime, to store the datetime to retain the history of last data update from API
Thank you for reading. Does this interests? Would you like to see an example?
Assumptions:
I have used ES6 statements to present code example.
The data is an empty object, but it can be array or primitive value.