Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispatching clear state action in redux

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?

like image 337
godsenal Avatar asked Dec 04 '17 09:12

godsenal


1 Answers

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

like image 62
João Cunha Avatar answered Sep 22 '22 15:09

João Cunha