Search code examples
reactjsredux

How to get back to the original state in redux?


I have to actions FETCH_REPOS and FILTER_BY_LANGUAGE. When the app runs, the repos are fetched from the server and loaded in the store.

Then I try to filter by language

case 'FILTER_BY_LANGUAGE':
  let newState =  { 
    repos:[...new Set(state.repos)]
         .filter(val => val.language == action.payload)
    }
    return newState

The scenario is, I fetch 30 repositories. Say 10 are JS, 10 PHP and 10 Node.

I then filter the JS repos. Now the store has 10 repos instead of 20, so when I try to filter again my PHP, those repos are go.

Show are refetch the data again or should I filter the data within the react props?

Here are the actions

export const fetchRepos = () => dispatch => {
    fetch('http://localhost:4000/originalrepos')
        .then(res => res.json())
        .then(repos => {
            let content = repos.map((data, i)=>{
                return {
                    title: data.name,
                    username: data.owner.login,
                    avatar: data.owner.avatar_url,
                    date: data.updated_at,
                }
            })
            dispatch({
                type: 'FETCH_REPOS',
                payload: content
            })
        })
}
export const filterByLanguage = language => dispatch => {
    dispatch({
        type: 'FILTER_BY_LANGUAGE',
        payload: language

    })
}

I fetchRepos on mount, then the FILTER_BY_LANGUAGE sort of reduces the store. An expected behaviour, so I'm wondering whether I need to run the same fetch within FILTER_BY_LANGUAGE or remove that action all together and take care of filtering the store at the props? Thought these are the reasons to use redux, right?


Solution

  • You can save your state whenever there's a state change with something like this:

    var stateHistory = []
    
    YourReducer = (state, action){
    
      //Whenever the reducer is called, it pushes to the history
      stateHistory.push(state)
    
      switch(action.type){
        ...
        case "UNDO":
          //fire the UNDO action to go back to the last recorded state
          return stateHistory.pop()
      }
    }
    

    You might want to check if the new state is the same as the last pushed state before adding it to the history object.