Persist store with Redux Toolkit in React-native - react-native

I am using redux-persist with redux toolkit.
here is my store configuration.
I haven't implemented or configured store before.
I intend to persist user state after login.
Currently after login, if I reload app in emulator it always goes back to login screen.
is my store configured properly?
updated store file:
import {configureStore} from '#reduxjs/toolkit';
import authReducer from '../features/login/authSlice';
import AsyncStorage from '#react-native-community/async-storage';
import {persistReducer, persistStore} from 'redux-persist';
import {combineReducers} from 'redux';
import hardSet from 'redux-persist/lib/stateReconciler/hardSet';
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';
const reducers = combineReducers({
auth: authReducer,
// other reducers goes here...
});
const persistConfig = {
key: 'root',
storage: AsyncStorage,
// stateReconciler: hardSet,
};
const _persistedReducer = persistReducer(persistConfig, reducers);
export const store = configureStore({
reducer: _persistedReducer,
});
export const persistor = persistStore(store);
My index.js file where i wrap my root component with PersistGate
import React from 'react';
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import {store, persistor} from './src/stores/store';
import {Provider} from 'react-redux';
import {storeUser, storeRefreshToken} from './src/features/login/authSlice';
import {PersistGate} from 'redux-persist/lib/integration/react';
const RNRedux = () => (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<App />
</PersistGate>
</Provider>
);
AppRegistry.registerComponent(appName, () => RNRedux);
Error I get currently:

I think you need to use persistStore. You should store your app store in persistStore and then use persistGate.
PersistGate delays the rendering of your app's UI until your persisted state has been retrieved and saved to redux.
So, your store file can be :
import { persistStore } from 'redux-persist';
const persistor = persistStore(store);
export { persistor, store };
And your app.js will be :
import { store, persistor } from 'path_to_your_store/store';
<Provider store={store}>
<PersistGate persistor={persistor}>
</App>
</PersistGate>
</Provider>

This appears to be an issue with redux-persist passing a function as an action type which is not recommended by the Redux devs. Redux Toolkit was developed with defaults to help avoid the creation of breakable code. It's RTK's default middleware "serializableCheck" that throws this error. This middleware can be disabled outright or just for specific actions, and both methods are provided by example in answers to this SO question. RTK middleware documentation here for quick reference.
Here's a blanket solution that should work for you:
- import {configureStore} from '#reduxjs/toolkit';
+ import {configureStore, getDefaultMiddleware} from '#reduxjs/toolkit';
...
export const store = configureStore({
reducer: _persistedReducer,
+ middleware: getDefaultMiddleware({
+ serializableCheck: false
+ }),
});
...

Related

Redux-persist not persisting with expo on reload

I am using following tech stack
react-native
expo
redux
redux-persist.
I have tried articles, docs as well as questions here also but not help. Its simply not persisting. I am using emulator and running through expo only. As soon i close the app and reload expo client it simply doesn't persist and ask me to login again.
I also tried using AsyncStorage but still not working.
Hers's my code:
index.js
import thunk from "redux-thunk";
import AsyncStorage from "#react-native-community/async-storage";
import ExpoFileSystemStorage from "redux-persist-expo-filesystem"
// import storage from 'redux-persist/lib/storage';
import { createStore, applyMiddleware, compose } from "redux";
import { persistStore, persistReducer } from "redux-persist";
import rootReducer from "./reducers/rootReducer";
import logger from "redux-logger";
const persistConfig = {
key: "root",
storage: ExpoFileSystemStorage,
whitelist: ["authReducer"],
};
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = createStore(
persistedReducer,
composeEnhancers(applyMiddleware(thunk, logger))
);
let persistor = persistStore(store);
export { store, persistor };
app.js
import React from "react";
import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/integration/react";
import { AppLoading } from "expo";
import { useFonts } from "#use-expo/font";
import { NavigationContainer } from "#react-navigation/native";
import { ThemeProvider } from "react-native-elements";
import { theme } from "./constants/ThemeConfiguration";
import { store, persistor } from "./store";
import RootNavigator from "./navigators/RootNavigator";
export default (App) => {
let [fontsLoaded] = useFonts({
"Lato-Regular": require("./assets/fonts/Lato-Regular.ttf"),
});
if (!fontsLoaded) {
return <AppLoading />;
} else {
return (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<ThemeProvider theme={theme}>
<NavigationContainer>
<RootNavigator />
</NavigationContainer>
</ThemeProvider>
</PersistGate>
</Provider>
);
}
};
rootReducer.js
import thunk from "redux-thunk";
import AsyncStorage from "#react-native-community/async-storage";
import { createStore, applyMiddleware, compose } from "redux";
import { persistStore, persistReducer } from "redux-persist";
import rootReducer from "./reducers/rootReducer";
import logger from "redux-logger";
const persistConfig = {
key: "auth",
storage: AsyncStorage,
};
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = createStore(
persistedReducer,
composeEnhancers(applyMiddleware(thunk, logger))
);
let persistor = persistStore(store);
export { store, persistor };
I got it fixed. Its not there in any documentation or article. The problem is with the persistConfig. Key which is root here. It should be the name of the reducer which we want to persist. In my case it was auth.
Updated persistConfig will be as follows:
const persistConfig = {
key: "auth",
storage: AsyncStorage,
};

Unable to handle error: `middleware is not a function' in redux-promise-middleware?

I am trying to use redux-promise-middleware in my app, but when I am trying to run my app error comes with an error message: 'middleware is not a function or middleware is null'.
I tried to use middleware without a function as suggested in redux async docs, but still error is coming.
configureStore.js
import { createStore, applyMiddleware } from 'redux'
import app from './reducers/index';
import PromiseMiddleware from 'redux-promise-middleware';
const configureStore = () => {
let middleware = applyMiddleware(PromiseMiddleware());
let store = createStore(app, middleware);
return store
};
export default configureStore;
index.js
import React from 'react'
import { AppRegistry } from 'react-native';
import App from './App';
import { Provider } from 'react-redux'
import configureStore from './configureStore'
const store = configureStore();
const ReduxMiddleware = () => {
<Provider store={store}>
<App />
</Provider>
}
AppRegistry.registerComponent('ReduxMiddleware', () => ReduxMiddleware);
Please anybody, suggest to me that why I am facing this error.
I am new to redux.
import promiseMiddleware from 'redux-promise-middleware';
composeStoreWithMiddleware = applyMiddleware(
promiseMiddleware,
)(createStore);
And not : PromiseMiddleware()
(not uppercase and w/o () )

Could not find "store" in the context of "Connect(App)" even after uses provider or connect

I'm trying to use redux in my project I make my code like tutorial but it won't work and give error
I see most of the question about this error but I already done what they say the soultion like I should warp my root componet with provider or use connect
Invariant Violation: Could not find "store" in the context of "Connect(App)". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(App) in connect options.
index.js
import React from 'react';
import {AppRegistry} from 'react-native';
import {Provider} from 'react-redux';
import App from './App';
import { name as appName } from './app.json';
import placesReducer from './src/store/reducers/places';
import{createStore} from 'redux'
import configureStore from './src/store/configureStore';
const store = configureStore();
const RNRedux = () => (
<Provider store={store}>
<App/>
</Provider>
);
AppRegistry.registerComponent(appName, () => RNRedux);
APP.js
import React, { Component } from "react";
import { StyleSheet, View } from "react-native";
import { connect } from "react-redux";
class App extends Component {
render() {
return (
<View style={styles.container}>
some code
</View>
);
}
}
const mapStateToProps = state => {
return {
some code
};
};
const mapDispatchToProps = dispatch => {
return {
some code
};
};
export default connect(mapStateToProps, mapDispatchToProps)(App);
my store
import {combineReducers, createStore} from 'redux';
import placesReducer from './reducers/places';
const rootReducer = combineReducers({
places: placesReducer
});
const configureStore = () => createStore(rootReducer)
export default configureStore;
const configureStore = () => createStore(rootReducer)
configureStore in this case is a variable with the return value of createStore, you most likely want it to be a function.
do you have to call configureStore as callback?
can you call it directly like that:
const configureStore = createStore(rootReducer);

How to persist redux store in React Native with redux-persist

I am using react-native with redux-persist and I cannot seem to get my store to persist into async storage. According to the redux-persist github repo, this may have to do with AsyncStorage being removed from react-native, but I cannot seem to figure out what needs to be done to fix the issue.
When my app launches I see the actions persist/PERSIST and persist/REHYDRATE fire in my redux devtools, but nothing ever is stored in async storage.
I thought I had set up my file as the redux-persist docs explained but I imagine I am missing something. I'm fairly new to Redux as it is so I may just be confused on something basic.
My Redux.config.js file ...
import React from 'react';
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import { Provider } from 'react-redux'
import thunk from 'redux-thunk';
import { initialState } from './initialState';
import { puppyReducer } from './reducers/puppies/puppyReducer';
import { uiReducer } from './reducers/ui/uiReducer';
import { userReducer } from './reducers/user/userReducer';
import { contentReducer } from './reducers/content/contentReducer';
import { persistStore, persistReducer, persistCombineReducers } from 'redux-persist';
import storage from 'redux-persist/lib/storage'
import logger from 'redux-logger';
import Navigation from './Navigation.config';
import { PersistGate } from 'redux-persist/integration/react';
const persistConfig = {
key: 'root',
storage: storage
}
const rootReducer = {
dogs: puppyReducer,
ui: uiReducer,
user: userReducer,
content: contentReducer
};
const reducer = persistCombineReducers(persistConfig, rootReducer);
const persistedReducer = persistReducer(persistConfig, reducer);
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(persistedReducer, initialState, composeEnhancers(applyMiddleware(thunk), applyMiddleware(logger)));
const persistor = persistStore(store);
// Wrap the redux State Provider around the Main Navigation Stack
function StateWrapper() {
return (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<Navigation />
</PersistGate>
</Provider >
)
}
export default App = StateWrapper;
I expect that this should load my persisted state when the app launches, and continue to update that persisted state as my redux state changes. As it stands currently, my state is updating fine, but nothing is persisted. There are no error messages showing.
I persist my redux store using AsyncStorage. Rather than using redux-persist's storage option, I have installed AsyncStorage from the #react-native-community. Just make sure that you link the dependency properly.
Then in my config.js file I import and use AsyncStorage as follows.
import AsyncStorage from '#react-native-community/async-storage';
const config = {
key: 'primary',
keyPrefix: '', // the redux-persist default `persist:` doesn't work with some file systems
storage: AsyncStorage,
};
Your issue could also be related to the keyPrefix try setting it to some value other than the default.
Try the following:
const reducer = persistCombineReducers(persistConfig, rootReducer);
const persistedReducer = persistReducer(persistConfig, reducer rootReducer);
This works for me:
//...
import {combineReducers} from 'redux';
import {persistReducer} from 'redux-persist';
const persistConfig = {
key: 'root',
storage: storage
}
const rootReducer = {
dogs: puppyReducer,
ui: uiReducer,
user: userReducer,
content: contentReducer
};
const persistedReducer = persistReducer(
persistConfig,
combineReducers(rootReducers)
);
//...

React Naitve Redux getState Undefined

I am trying to Firebase Phone Authentication with React-redux. but i am getting getState undefined in Action file.
i am getting "confirmResult.confirm is undefined"
Action.Js
const onCodeDispatched = (code) => {
return (dispatch, getState) => {
console.log(getState())
getState().auth.confirmResult.confirm(code)
.then(user => onLoginSuccess(dispatch, user))
.catch(error => onCodeConfirmError(dispatch, error));
}
}
App.js
import React from 'react'
import {Provider} from 'react-redux'
import {createStore, applyMiddleware, compose} from 'redux'
import thunkMiddleware from 'redux-thunk'
import reducers from '../reducers'
import App from './App'
import {persistStore} from 'redux-persist'
import {PersistGate} from 'redux-persist/es/integration/react'
const middleware = [thunkMiddleware]
const store = compose(applyMiddleware(...middleware))(createStore)(reducers)
console.log(store)
let persistor = persistStore(store)
class Root extends React.PureComponent {
render() {
return (
<Provider store={store}>
<PersistGate persistor={persistor}>
<App />
</PersistGate>
</Provider>
)
}
}
export default Root
i am new in react-redux it is very confusing me i already read many articles i already spent many days finding the error can you please give me some idea why getState is returning Undefined.
Try to split how are you constructing the store. You can begin creating just a simple instance of store, like this:
const store = createStore(reducers, yourInitialState)
Then print the store and see what happened. If everything is okay, try to use compose, applyMiddleware, and thunk like that:
const store = createStore(
reducer,
compose(
applyMiddleware(thunk),
DevTools.instrument() // this is a really helpful instrument
)
)
If you have doubts just ask or follow the official doc from Redux website