Dan Dan - 2 months ago 37
React JSX Question

How to cleanup dirty state in React and Redux?

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?

Answer

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.

Comments