beekai-oss / little-state-machine

📠 React custom hook for persist state management
https://lrz5wloklm.csb.app/
MIT License
1.48k stars 53 forks source link

unable to clear store #115

Closed NealWilxite closed 2 years ago

NealWilxite commented 2 years ago

I am using lsm with react-router for a wizard on a client's site and I need to reset the store when a user returns to the wizard landing page. I found this solution in stack overflow (https://stackoverflow.com/questions/64822032/react-little-state-machine-clear-data) but I cant get it to work. I cant show the full application, but from the below can you see anything wrong with what I have done.

Using

    "react-router-dom": "^6.2.1",
    "little-state-machine": "^4.2.0",
    "little-state-machine-devtools": "^2.0.1",

App.js

createStore({
  data
});

function App() {

    return (
      <StateMachineProvider>
        <DevTool />
        <div className="container">
          ...
          <Router>
            <Steps />
          </Router>
        </div>
      </StateMachineProvider>
    );
  }

  export default App;

Steps.js

....
import { useStateMachine } from "little-state-machine";
import clearAction from "./lsm/actions/clearAction";
...

export default () => {
     ....
    const location = useLocation();
    const { state, actions } = useStateMachine({ clearAction });
    ...

    useEffect(() => {

        let step = location.pathname.split("/")[2];
        // landing page location = http://site.co.uk/wizard
        // steps have url = http://site.co.uk/wizard/step[1-4]
        if(!step){

            actions.clearAction();

        }

    }, []);

 return (...);
 };

clearAction.js

 export default function clearAction(state, payload) {
    return {};
  }

I even tried to use window.__LSM_RESET(), sessionStorage.removeItem('LSM__') and sessionStorage.clear(). None of these work.

Is there a simpler way to reset/clear the store from within a component?

bluebill1049 commented 2 years ago

should be able to do easily with a clearAction as above. can you share a codesandbox?

NealWilxite commented 2 years ago

the wizard is part of the clients site, so it is a little difficult to extract but i'll give it a try.

NealWilxite commented 2 years ago

I think I fixed the issue. Was peppering my code with state updaters that were conflicting with each other.