Make redux-persist to notify me when data are restored - reactjs

I have large amount of data that I'm storing in local storage using react persist. What I need is to know when persist data were restored in my reducer (when app is loading). I need to validate data version and I need to generate lookup object (which redux-storage us unable to store, probably because because it has around 65405 records/fields).
Anyway I would like to know when react-persist is loading my data so I can work with them. How do I achieve this?

There are two special actions in redux-persis: PERSIST and REHYDRATE.
The PERSIST action has been dispatched and then with REHYDRATE, the saved object of the store will be load and injected into the current redux store. So, you can import them into your reducer functions and be aware of persisting status.
You need to manipulate the data before re-hydrated them with persistor, but I recommend doing a simpler approach to handle this case.
For example, there is a data value (which is contain 65405 records):
case DATA_ARRIVED_SUCCESSFULLY:
return {
...state,
data: actin.payload
}
Now, before persisting and before putting the payload on data, you can check and validate your data:
const sampleValidatorData = (myData) => {
// do something with myData
}
case DATA_ARRIVED_SUCCESSFULLY:
return {
...state,
data: sampleValidatorData(actin.payload)
}
Now, your saved data (with persistor) will be valid.

Related

State changes in Redux-Saga

I have a simple React App. It allows a user to edit a form to update data in a database. On Submit the page generates an action with the form data. A Redux Saga yields to the action and asynchronously updates the database. This all works.
However in one case the update is slightly more involved. Not only must new data be added but any data deleted on the form must be deleted from the database in a series of API calls. To do this I need to know what has changed (e.g. what has been deleted) rather than just the new state.
How can my saga have access to this information? I could calculate it in the reducer because that has access to the previous state but it is commonly held to be an anti-pattern for the reducer to then dispatch a new action.
Sagas have a select effect available, which just runs a selector function and returns the extracted state. You can use this to retrieve the old and new items from the Redux store, and deal with the changes from there:
function* handleFormUpdates() {
const oldItem = yield select(selectOldItem);
const newItem = yield select(selectNewItem);
const changes = diffTheItems(oldItem, newItem);
// make API calls to deal with changes appropriately
}
Overall, this is a good reason to keep the "temporary" or "draft" state in Redux, so that you can make use of both the "current" and "draft" values in your logic.
I discussed some related concepts in my blog posts Practical Redux, Part 7: Form Change Handling, Data Editing, and Feature Reducers and Practical Redux, Part 8: Form Draft Data Management
...any data deleted on the form must
be deleted from the database in a series of API calls. To do this I
need to know what has changed (e.g. what has been deleted) rather than
just the new state.
If I understand correctly you have form state saved in a redux store and you need to know when and what has changed. You could create your own watcher saga:
function* watchFormUpdates(){
while (true) {
const oldFormState = yield select(selectors.selectFormState);
const action = yield take (actionTypes.FORM_UPDATE); // wait until action is dispatched
const newFormState = yield select(selectors.selectFormState); // at this point store has been updated
// compare oldFormState with newFormState...
if(oldFormState.hasSubscription && !newFormState.hasSubscription) {
yield fork(deleteSubscriptionSaga); // start non-blocking worker task
// or just dispatch action - yield put(actionCreators.deleteSubscription());
}
}
}

Where should I load data from server in Redux + ReactJS?

For example I have two components - ListOfGroupsPage and GroupPage.
In ListOfGroupsPage I load list of groups from the server and store it to the state.groups
In route I have mapping like ‘group/:id’ for GroupPage
When this address is loaded, the app shows GroupPage, and here I get the data for group from state.groups (try to find group in state via id).
All works fine.
But if I reload page, I'm still on page /group/2, so GroupPage is shown. But state is empty, so the app can't find the group.
What is the proper way to load data in React + Redux? I can see this ways:
1) Load all data in root component. It will be very big overhead from traffic side
2) Don't rely on store, try to load required data on each component. It's more safe way. But I don't think that load the same data for each component - it's cool idea. Then we don't need the state - because each component will fetch the data from server
3) ??? Probably add some kind of checking in each component - first try to find required data in store. If can't - load from the server. But it requires much of logic in each component.
So, is there the best solution to fetch data from server in case of usage Redux + ReactJS?
One approach to this is to use redux-thunk to check if the data exist in the redux store and if not, send a server request to load the missing info.
Your GroupPage component will look something like
class GroupPage extends Component {
componentWillMount() {
const groupId = this.props.params.groupId
this.props.loadGroupPage(groupId);
}
...
}
And in your action...
const loadGroupPage = (groupId) => (dispatch, getState) => {
// check if data is in redux store
// assuming your state.groups is object with ids as property
const {
groups: {
[groupId]: groupPageData = false
}
} = getState();
if (!groupPageData) {
//fetch data from the server
dispatch(...)
}
}
I recommend caching the information on the client using localstorage. Persist your Redux state, or important parts of it, to localstorage on state change, and check for existing records in localstorage on load. Since the data would be on the client, it would be simple and quick to retrieve.
The way I approach this is to fetch from the server straight after the store has been created. I do this by dispatching actions. I also use thunks to set isFetching = true upon a *_REQUEST and set that back to false after a *_SUCCESS or *_FAILURE. This allows me to display the user things like a progress bar or spinner. I think you're probably overestimating the 'traffic' issue because it will be executed asynchronosly as long as you structure your components in a way that won't break if that particular part of the store is empty.
The issue you're seeing of "can't get groups of undefined" (you mentioned in a comment) is probably because you've got an object and are doing .groups on it. That object is most likely empty because it hasn't been populated. There are couple of things to consider here:
Using ternary operators in your components to check that someObject.groups isn't null; or
Detailing in the initialState for someObject.groups to be an empty array. That way if you were to do .map it would not error.
Use selectors to retrieve the list of groups and if someObject.groups is null return an empty array.
You can see an example of how I did this in a small test app. Have a look at specifically:
/src/index.js for the initial dispatch
/src/redux/modules/characters.js for the use of thunks
/src/redux/selectors/characters.js for the population of the comics, series, etc. which are used in the CharacterDetails component

Redux-persist react native AsyncStorage Object Map serialization

I am using redux persist to automatically persist and rehydrate the state on application launch as described in the docs, specifically using AsyncStorage: https://github.com/rt2zz/redux-persist.
It works correctly for String. That is all state which is store as a String is persisted and rehydrated correctly.
However for custom object maps it does rehydrate the state correctly. I am pretty sure this is because Strings are serializable and object maps aren't.
This is the reducer where productTypeToProducts is represents that map. When Re- hydrated is it empty
case 'RECEIVE_ALL_PRODUCTS':
return Object.assign({}, state, {
productTypeToProducts: action.productTypeToProducts
});
Hence I need to use something like JSON.stringify to covert my state tree into JSON.
How do I implement this so that on application launch the the object state (not the JSON) is automatically rehydrated. (I am guessing this has something to with using transforms in the docs ?)
It seems like by default AsyncStorage used in conjuction with redux-persist, does properly serialize an array of object. So I converted the Map to Array below in my reducer and it properly hydrated the state.
case 'RECEIVE_ALL_PRODUCTS':
let productsObject = {};
action.productTypeToProducts.forEach((value,key)=>{
productsObject[key] = value
});
return Object.assign({}, state, {
productsAsObject: productsObject,
});

using multiple redux stores one for each app user

in a react native app, i'm using redux. currently the whole app have single store and i use redux-persist to cache store to localstorage.
my app is username and password protected, you must create account to use it.
now i want to provide ability so that my user can switch between his accounts -if he have more than one account- . this is causing lots of trouble because now i have to clear storage and reset state everytime user switch between accounts.
so i was considering may be i can use multiple stores, one for every users ?
for example my app state looks like
{
chat:{},
highscores:{},
gameHistory:{},
}
now if a user have account lets say User1#gmail.com the state will be populated with his data. and his state will be saved to LocalStorage,
once he switch account to User2#gmail.com now i have to reset the app to its initialState, then somehow load the User2 state from localStorage
i dont want the state of the app to be lost everytime user switch between accounts.
so i was considering may be in this case it would be a good option to use a multiple Redux Stores, one for every user.
did anyone had an app that is designed to be used by multiple users before ?
how can we do this in redux ?
Well Answer above work fine, but since i'm using ImmutableJs, having a deeply nested objects can really be hard to handle.
so i ended up namespacing the Storage Key with user_id.
so now when ever i switch user, i just flush the whole store with this specefic user data from localStorage, or AsyncStorage.
i wrapped rootReducer in a simple reducer to handle this.
function makeRootReducer(rootReducer){
return function reducer(state, action){
if(action.type==='SWITCH_USER'){
//LOAD USER DATA..
const data = JSON.parse(localStorage.getItem("store.user."+action.id)||"{}");
return makeInitialData(data); //this just return initialData.
}
let newState = rootReducer(state, action);
//simple save state to localStorage if state changed
if(state !== newState)localStorage.setItem('store.user.'+state.user_id',JSON.stringify(newState);
return newState;
}
}
I don't think having a store for each user is a good idea. See this SO answer: https://stackoverflow.com/a/33633850/3794660
Why don't you namespace the data you have in your reducer by user id? Something like this:
{
currentUserId: "1",
chat:{ "1": { // Chats for user id 1 }, "2": { // Chats for user id 2 }},
highscores:{ // Same structure as above },
gameHistory:{ // Same structure as above },
}
When you switch user account, you simply update the currentUserId in the state.
I'd recommend using selectors to encapsulate the logic to read the data from the store.
A simple selector to get all the chats for the current account could look like this:
const getCurrUserId = state => state.currentUserId
const getChats = state => {
const userId = getCurrUserId(state);
return state.chat[userId];
}
You then use your simple getChats selector in your mapStateToProps to pass the data to your components. In this way you encapsulate the logic to retrieve the data from the state and your components don't need to know these details, so you're free to change your strategy if you need to.

How to persist certain redux store properties to disk?

In my redux app I have some settings that should be persisted to disk when they change (as JSON file) and loaded with the app (to fill the initial state of the store).
I guess app settings are state, so they belong in the store. Then I have actions that modify settings, either like SETTINGS/CHANGE with payload {name:'settingName', value: 'settingvalue'} or fine grained like SETTINGS/UNITS with payload 'metric' or 'imperial'.
Now I need something that intercepts certain state changes/action submissions and persist them to disk as serialized JSON. Is this something the settings reducer should do itself or better some kind of middleware that can perform this async in the background?
How would that look like in code?
You may use localStorage API as krs said. Care because it only allows string values, so you may need to stringify your objects before storing them:
var config = {
foo: 'foo',
bar: 'bar'
}
// Store:
localStorage.setItem('config', JSON.stringify(config));
// Get
JSON.parse(localStorage.getItem('config'));

Resources