Search code examples
javascriptreactjsflux

SPA when route change reset store value to default


For example there are two components A and B in different state named /a and /b

All data is set in store data.

eg:

a.store.js

a:{
    data:1
}

setData(data){
  this.a.data = data;
}

If you change data in A component a.store.js data will be changed too.

handleClickA:function(){
    AStore.setData(2) // change data of store to 2
}

When out of A component and enter B and reenter A data is 2 instead of 1;

I have tried reset value in unmont lifecycle it can work if set a.data to 1;

but If a is a large object I have to rewrite lots of code to reset.

If you have any good ideas, please tell me how to solve it.\

Thanks


Solution

  • What code do you use for resetting? It should be simple.

    // A store
    const initialState = {
      // your large object
    };
    
    A = {
      state: initialState,
      reset: function() {
        this.state = initialState;
      },
      setData: function(data) {
        // your implementation
      }
    };
    
    // Then you just
    componentWillUnmount: function() {
      A.reset();
    }