byte-fe / react-model

The next generation state management library for React
235 stars 22 forks source link

Persistance not working as expected: initialState is not used #131

Closed muescha closed 4 years ago

muescha commented 4 years ago

the debug in console prints the saved and also changed state from localStorage. but it not get initialized with the initalValue - only with the defaultUser :/

export interface User {
  trips: Trip[];
  name: string;
  id: number;
}

const defaultUser: User = {
  id: defaultTrips.length + 1,
  name: "User1",
  trips: defaultTrips
};

interface StateType {
  user: User;
}

const model: ModelType<StateType, ActionParams> = {
  state: {
    user: defaultUser
  },
  actions: {
    // actions here
  }
}

const persistMiddleware: Middleware = async (context, restMiddlewares) => {
  localStorage.setItem('__REACT_MODEL__', JSON.stringify(context.Global.State))
  await context.next(restMiddlewares)
}

actionMiddlewares.push(persistMiddleware)

let initalValue = JSON.parse(localStorage.getItem('__REACT_MODEL__')||"{}");
console.log("initial: start")
console.log(initalValue); // here the changed and saved State is printed
console.log("initial: end")
export default Model(model, initalValue)
ArrayZoneYour commented 4 years ago

(。・_・。)ノI’m sorry for the late reply. @muescha persistMiddleware only works after actions running and only do the write stuff, If you want to use state from Persistance storage, I think you need a extra step:

const model: ModelType<StateType, ActionParams> = {
  state: {
   // user: defaultUser
    user: JSON.parse(localStorage.getItem('__REACT_MODEL__'))['you model name']
  },
  actions: {
    // actions here
  }
}
muescha commented 4 years ago

thx

i used the code from this example:

https://github.com/byte-fe/react-model#how-can-i-make-persist-models