I'm using redux in my react project. My question is how to clear state when some works that use state finished.
For example, I have search
state in my redux store.
search:{
status: 'INIT',
result: [],
}
Since my search is an async request, it has status
field.
when the user searches a word, it will dispatch 'FETCH_SEARCH' to make status to 'LOADING'.
when fetch done, it will dispatch 'SUCCESS_SEARCH' or 'FAILURE_SEARCH' to make status 'SUCCESS' or 'FAILURE'.
And in my component that shows the result of a search, it renders depend on search
state's status. If a status is 'SUCCESS', it will render the result of the search.
So far, there is no problem.
but what if the user has searched before and try to search again after some works? Since the user has successfully searched before, search
state has 'SUCCESS' state. So my component will render 'unwanted' result.
So currently, i dispatch 'CLEAR_SEARCH' action to initialize search
state.
My question is how to clear redux state after some submission has done. Am i doing correctly? Or is it anti-pattern?
I've done this before and what I do is follow a workflow.
After a search submission you shouldn't clear state. You should reset it when the user searches again.
Let's say the user searches "Term A". You "SEARCH_SUCCESS" is set and it's rendering the results. When he searches again put that state to "SEARCHING" or "LOADING" as you have it.
Now in your render method if you have something like
// etc..
if (isLoading) {
return <LoadingComponent />
}
// etc..
You will render a loading before rendering any results. Then your search action should set either the SUCCESS or FAILURE and if you have your components mapped out correctly it should be really straightforward.
EDIT
After a brief discussion in the comment section you wanted INIT only at the start (the first ever time it's rendered) but then resetting the state still.
So you can go for this workflow:
First time: -> INIT -> SEARCH_TRIGGERED -> LOADING -> SUCCESS or FAILURE
Second time (still in same screen): -> SEARCH_TRIGGERED -> LOADING -> SUCCESS or FAILURE
And then you would have the desired workflow.
Hope I helped
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With