FormidableLabs / freactal

Clean and robust state management for React and React-like libs.
MIT License
1.65k stars 47 forks source link

Usage with react-router #80

Closed jelmerdemaat closed 6 years ago

jelmerdemaat commented 6 years ago

Hi!

Do you have any tips for using it with react-router? I'm running into issues when changing pages. The problem is that it seems to fall back to the "previous" state e.g. when using the back button of the browser. It doesn't save the changes made in another route.

Considering this code:

import React, { Component } from "react";
import { BrowserRouter, Route } from "react-router-dom";
import { provideState, injectState, update } from "freactal";

import App from './App';
import Home from './Home';
import TestPage from './TestPage';

const wrapComponentWithState = provideState({
    initialState: () => { counter: 0 },
    effects: {
        increase: update(state => ({ counter: state.counter + 1 })),
        decrease: update(state => ({ counter: state.counter - 1 }))
    }
});

const WrappedApp = wrapComponentWithState(injectState(App));

const Root = (
    <BrowserRouter>
        <WrappedApp>
            <Route exact path="/" component={Home} />
            <Route exact path="/test" component={TestPage} />
        </WrappedApp>
    </BrowserRouter>
);

(The code is somewhat simplified.)

Whenever you update the counter in route "/" the changes are preserved when navigating to "/test". But when changing the count inside this component (TestPage), the changes are not preserved when going back to Home. They get reset to the value that it had previously on the home route.

Am I doing something wrong? I looked for information on usage with react-router, but I couldn't find it here or on Stackoverflow.

Thanks!

Jascha-Sundaresan commented 6 years ago

what are you doing in home and test page? are you only injecting state into them or also wrapping them with state?

jelmerdemaat commented 6 years ago

I have probably found the bug in my example:

const wrapComponentWithState = provideState({
-   initialState: () => { counter: 0 },
+   initialState: () => ({ counter: 0 }),
    effects: {
        increase: update(state => ({ counter: state.counter + 1 })),
        decrease: update(state => ({ counter: state.counter - 1 }))
    }
});

Working example: https://www.webpackbin.com/bins/-KxSXPrfybcyAK9rt6kN

The returned initial state was never a correct object. My bad. Still wondering if it would work correctly now in my app. I'll test it later. But untill then, case closed.

divmain commented 6 years ago

Thanks for circling back to let us know @jelmerdemaat.