FormidableLabs / freactal

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

React Native database? #95

Closed stovmascript closed 6 years ago

stovmascript commented 6 years ago

Thanks for this awesome lib! I'm really enjoying freactal and would love to use it in React Native. What would be the best way to load and inject my app state from a database?

I'm using Expo's SecureStore to save stuff to iOS' Keychain and Android's SharedPreferences. I haven't tried it yet, but would assume that saving would be done in effects or middleware. But loading on the other hand, I'm not sure where to implement. Would the hydrate and initialize functions for SSR be of any use?

bingomanatee commented 6 years ago

keep in mind this code was from before I noticed the initialize method but: I have a list of key state parameters that I serialize to the session state object in the browser and/or pull from an API:

    middleware: [
      (context) => { // save select values into session
        console.log('context state = ', context.state);
        if (sessionStorage && context.state) {
          if (!context.state.backgrounds) {
            console.log('no backgrounds');
          }
          for (let def of LOAD_STATES) {
            if (!def.loadFromAPI) {
              putInSession(def.name, context.state[def.name] || null, def.type);
            }
          }
        }
        return context;
      } ,
      (context) => { // load values from API
        for (let def of LOAD_STATES) {
          if (def.loadFromAPI && (!def.loadStart)) {
              def.loadStart = true;
              axios.get(`${config.API_ROOT}choices/${def.name}`)
                .then((result) => {
                let value = result.data;
                context.effects.fromAPI(def.name, value);
                def.loadDone = true;
            });
            }
            //putInSession(def.name, context.state[def.name] || null, def.type);
          }
        return context;
      }
    ]
divmain commented 6 years ago

initialState would definitely be a natural place to do this. The docs call out SSR scenarios as the prime example, but it is really intended for any case where you need to set state when the stateful component is originally loaded. In the case of an app-wrapper, it would make sense to pull in saved state there.

hydrate does some special work to match server-rendered components with their locally-rendered stateful counterparts. You shouldn't need to use it here.

Sorry for very delayed reply, but hope you were able to work things out. Going to close this as resolved, but please do feel free to re-open if you'd like additional help.