Actually, I was making an example project similar to Google search using Google API. Here is my code. The function below fetches data from the API and returns json formatted result and it takes a while since I need to call this function several times at once.
export async function getSearchResult(searchValue, searchPage){
var link = "https://api.serpwow.com/live/search?api_key=<MY_API_KEY>&q="+searchValue+"&page="+searchPage;
var dt;
await axios
.get(link)
.then(response => response.data)
.then((data) => {
dt = data;
});
return dt;
}
The code updates the initalState, with the return value. Here is my problem. The client side renders the old result before the fetching finishes. So user needs to refresh the list to get a new result. What can I do? I tried to set timeout function before display the data, but I know that's not the best solution for mine. Thanks.
You can achieve this by setting loading
to true
before doing axios call. In your component, show a loading indicator when loading
is true
. Once Axios call response arrives, dispatch an action to set loading
to false
& data
to dt
. Below code gives idea of how to achieve this:
export async function getSearchResult(searchValue, searchPage){
var link = "https://api.serpwow.com/live/search?api_key=<MY_API_KEY>&q="+searchValue+"&page="+searchPage;
var dt;
// dispatch action to set `loading` to `true`
await axios
.get(link)
.then(response => response.data)
.then((data) => {
dt = data;
});
// dispatch action to set `data=dt` & `loading` to `false`.
}