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'));
Related
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.
I am currently developing an analytics dashboard in React/Redux that is similar to this:
Users of the dashboard will be able to add and remove tiles to customise the dashboard to their own needs, and the configuration of the tiles is stored and retrieved in an API.
The storing of the data for the configuration of tiles seems to fit well with the global state model:
On load, the dashboard component dispatches a 'loadTiles' action
The action fetches the tiles data and passes it to the 'tiles' reducer
From there it goes into the store/global state.
In mapStateToProps, the data is accessed from state.app.tiles
However, a problem arises when populating the data for each tile. The number of tiles and nature of the data is dynamic, so reducers can't be set up ahead of time.
This could be solved by each component managing their own state (as in pure/traditional React using componentWillMount etc) but this will violate some of the architectural principals that have been laid out for the rest of the project (ideally everything is to be managed in global state).
The only way I can see of storing the data is global state would be to have an analytics with a dynamic array of the various data sets, which sounds messy to me.
Is local component state the best solution here? or can this be done in global state cleanly? Are there any example of Redux using queries that are dynamically specified?
One thing you can do is the usage of an ID for each Tile. So your state could look like that:
{
tiles: {
tile1: {},
…
tile100: {}
}
}
Than, in the mapStateToProps() function you can use own props like so:
function mapStateToProps(state, ownProps) {
//test if it exists
if (state.tiles[ownProps.id]) {
return { tileData: state.tiles[ownProps.id] }
}
else
{
return { tileData: <default state> }
}
}
The important part is to hand over a unique ID for each tile, when those are created, one way could be that:
<Tile id={uuid()} other="stuff" />
whereby the uuid() method can be created as described here
I once had an similar issue, have a look here if you want to see a more complicated solution using an higher order component (its my own unaccepted answer). All in all, the above is the simplest solution IMHO.
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
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,
});
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.