How to return redux state to initial state?


How to return redux state to initial state?



I'm having surprisingly difficult time figuring this out, essentially I'm trying to set state to initial state, so far I tried:


// -- Initial state ------------------------------------------------------------
const INITIAL_STATE = {
search: {
listings:
},
listings:
}

// -- Story structure for story editor -----------------------------------------
export default function(state = INITIAL_STATE, action) {
switch(action.type) {
case ACTIONS.RESET_STATE:
return { ...state, INITIAL_STATE }
default:
return state;
}
}



this just adds initial state to existing one


case ACTIONS.RESET_STATE:
return { ...state, state = INITIAL_STATE }



this returns error


case ACTIONS.RESET_STATE:
return { ...state, state: INITIAL_STATE }



this is adding initial state to existing one gain


case ACTIONS.RESET_STATE:
return { ...state, search: { listings: }, listings: }



This works, but I start getting weird mutation errors.




3 Answers
3



If you simply want to reset state completely, just return the value of INITIAL_STATE:


INITIAL_STATE


export default function(state = INITIAL_STATE, action) {
switch(action.type) {
case ACTIONS.RESET_STATE:
return {
search: {
listings:
},
listings:
};
default:
return state;
}
}



If you want to keep the INITIAL_STATE in a single place. Change the initial state creator to a function:


INITIAL_STATE


function get_INITIAL_STATE => {
return { search: {
listings:
},
listings:
}
}

export default function(state = get_INITIAL_STATE(), action) {
switch(action.type) {
case ACTIONS.RESET_STATE:
return get_INITIAL_STATE();
default:
return state;
}
}





For some reason returning INITIAL_STATE returns it how it was before
– Ilja
Feb 18 '16 at 9:37





@Ilja see updated, thanks.
– Davin Tryon
Feb 18 '16 at 9:41



An even easier way is to just return INITIAL_STATE.


case ACTIONS.RESET_STATE:
return INITIAL_STATE;



The proposed solution of Andreas is right, but has potential problem with imutables. This generates always new object.


case ACTIONS.RESET_STATE:
return { ...INITIAL_STATE };






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

List of Kim Possible characters

Audio Livestreaming with Python & Flask

NSwag: Generate C# Client from multiple Versions of an API