Reputation: 387
I have question about clearing redux state.
I have state named search
for searching address with fetching. It's structure like this
search:{
status: 'INIT',
results: [],
}
status
is a flag for async request something like 'SUCCESS' or 'FAILURE'.
results
is a result of fetching.
When user search address with some search word, results has result of fetching. And My component render like this,
<div>
{this.props.results.map((result,i)=>{
<div>{result}</div>
)}
</div>
So my problem is when user try to search again after some other works, component render previous search result because results
is not clear.
Currently, I dispatch action 'CLEAR_SEARCH' that initialize search
state, after works using results has done. But i think it's not a good way.
Is there any better idea?
Upvotes: 0
Views: 719
Reputation: 6171
When you start initialising the new request, you can dispatch an action call START_LOADING
dispatch(startLoadingAction())
try {
const result = await fetch...
dispatch(successAction(result));
} catch {
dispatch(failureAction());
}
then handle it like this:
case START_LOADING:
state = {
status: 'LOADING',
result: [],
};
break;
Upvotes: 2
Reputation: 1930
It's a common pattern to have requests in redux look more like
{
isLoading: false,
data: [],
error: false,
isLoaded: true,
hasFailed: false,
}
so that when you clear or re-issue the search result the status of the request changes, and you can display based on the request instead of just the presence of data.
Upvotes: 0