-1

I am facing this issue for weeks.
I asked another question before, and I found out that this problem has to do with dirty state.

Basically, I created a page with a list of articles, and when you click one of them, it will take you to see an article. I am making AJAX GET request with componentDidMount for both articles and an article(you can see this code in here).

I tried to find out a solution without asking here, but I couldn't. I am guessing that I have to add componentWillUnmount method in ArticlePage to cleanup my dirty state from previous page.
This is my action fetching articles for a list and each article.

export function fetchArticles(){
   return (dispatch) => {
      axios.get('/api/articles').then(({data}) => {
         dispatch({
            type: FETCH_ARTICLES,
            payload: data
         })
      })
    }
}
export function fetchArticle(id){
    return (dispatch) => {
       axios.get(`/api/articles/${id}`).then(({data}) => {
          dispatch({
             type: FETCH_ARTICLE,
             payload: data
          })
       })
    } 
 }

this is my reducer:

export default function(state=[], action){
   switch (action.type) {
      case FETCH_ARTICLES:
         return action.payload;
      case FETCH_ARTICLE:
         return action.payload;
    default:
         return state;
   }
 }

How can I cleanup dirty state?

Community
  • 1
  • 1
kay
  • 1,369
  • 4
  • 15
  • 27

1 Answers1

1

Your reducer should look like this:

export default function(state=[], action){
   switch (action.type) {
      case FETCH_ARTICLES:
         return action.payload;
      case FETCH_ARTICLE:
         return action.payload;
      case RESET_ARTICLE:
         return []; // return an empty state here.
    default:
         return state;
   }
 }

and in your component in componentWillUnmount trigger RESET_ARTICLE action.

Anubhav Gupta
  • 1,176
  • 11
  • 12
  • @Dan So have you dispatched the action on the ```componentWillUnmount?``` Is that action dispatched? If not then you are not properly unmounting the component. – skay- Sep 07 '16 at 07:55
  • @skay- Yeah I did, and if I looked at Diff in my Redux DevTools, a state actually changes to [ ]. However, I still cannot go back to the previous page. – kay Sep 07 '16 at 09:03
  • 1
    @Dan what do you mean you cannot go back to the previous state? Changing routes is another story. The impression i get from your question is that you simply want to reset the state not change page. – skay- Sep 07 '16 at 09:28
  • @skay- oh, I am sorry. you are right. I only asked how I reset my state here. I was including the another question I asked. I am just gonna accept this as the answer. sorry about that. – kay Sep 07 '16 at 09:41