Navigate in action with redux, debug with reactotron error - react-native

I try to navigate inside actions of redux, but the command NavigationActions.navigate don't worked, so I installed reactotron to try debug with reactotron, but this cause the error of image, below are the code and de error. Some help me please.
The action
export function* searchByID(action) {
try {
console.log('action', action);
const response = yield call(apiGetProdutoByID, action.idProduto);
console.log('produto', response);
yield put({
type: TypesProdutos.SEARCH_BY_ID,
produto: response.data.data.obj,
});
const produto = yield select(state => state.produtos);
console.log(produto);
**yield put(
NavigationActions.navigate({
routeName: action.route,
params: {produto: produto},
}),**
);
} catch (error) {
console.log(error);
yield put({type: TypesProdutos.FAIL});
}
}
ReactotronConfig.js
import Reactotron from 'reactotron-react-native';
import AsyncStorage from '#react-native-community/async-storage';
import {reactotronRedux as reduxPlugin} from 'reactotron-redux';
import sagaPlugin from 'reactotron-redux-saga';
const reactotron = Reactotron;
Reactotron.setAsyncStorageHandler(AsyncStorage) // AsyncStorage would either come from `react-native` or `#react-native-community/async-storage` depending on where you get it from
.configure() // controls connection & communication settings
.useReactNative() // add all built-in react native plugins
.use(reduxPlugin())
.use(sagaPlugin())
.connect(); // let's connect!
export default reactotron;
index.js
if (__DEV__) {
import('./ReactotronConfig').then(() => console.log('Reactotron Configured'));
}
import {AppRegistry} from 'react-native';
import App from './src';
import {name as appName} from './app.json';
AppRegistry.registerComponent(appName, () => App);
index.js (store)
import {createStore, applyMiddleware} from 'redux';
import createSagaMiddleware from 'redux-saga';
import rootReducer from './ducks';
import rootSaga from './sagas';
import Reactotron from 'reactotron-react-native';
const sagaMonitor = Reactotron.createSagaMonitor;
const sagaMiddleware = createSagaMiddleware({sagaMonitor});
const middleware = applyMiddleware(sagaMiddleware);
const store = createStore(rootReducer, middleware);
sagaMiddleware.run(rootSaga);
export default store;
error:
error

After command npm install and make this modifications in the file where I export store, the app worked.
import {createStore, applyMiddleware, compose} from 'redux';
import createSagaMiddleware from 'redux-saga';
import rootReducer from './ducks';
import rootSaga from './sagas';
import Reactotron from 'reactotron-react-native';
import ReactotronConfig from '../../ReactotronConfig';
const sagaMonitor = Reactotron.createSagaMonitor;
const sagaMiddleware = createSagaMiddleware({sagaMonitor});
const middleware = applyMiddleware(sagaMiddleware);
const store = createStore(
rootReducer,
compose(
middleware,
ReactotronConfig.createEnhancer(),
),
);
sagaMiddleware.run(rootSaga);
export default store;

Related

Redux Toolkit :Error: "reducer" is a required argument, and must be a function or an object of functions that can be passed to combineReducers

With this code i got no error.
import {combineReducers, configureStore} from '#reduxjs/toolkit';
import {menuReducer as menu} from './menu';
import {cartReducer as cart} from './shoppingCart';
import {optionsReducer as options} from './optionsItem';
import {homeReducer as home} from './home';
import {rewardReducer as reward} from './reward';
import {ordersReducer as orders} from './orders';
import {authReducer as auth} from './auth';
import giftCardReducer from '../store/giftCard';
import paymentMethodReducer from './paymentMethod';
import paymentToken from "./paymentToken";
import qRCode from "./qRCode";
import orderHistory from './orderHistory';
import orderDetail from './orderDetail';
import showCompletedOrder from './showCompletedOrder';
import paymentOptionsSummary from './paymentOptionsSummary';
import usersUpdate from './usersUpdate';
import referAFriend from './referAFriend';
import resetPassword from './resetPassword';
const reducer = combineReducers({
menu,
auth,
giftCardReducer,
paymentMethodReducer,
cart,
options,
orders,
home,
reward,
paymentToken,
qRCode,
orderHistory,
orderDetail,
showCompletedOrder,
paymentOptionsSummary,
usersUpdate,
referAFriend,
resetPassword
});
export {menuActions} from './menu';
export {cartActions} from './shoppingCart';
export {optionsActions} from './optionsItem';
export {ordersActions} from './orders';
export {authActions} from './auth';
export {homeActions} from './home';
export {rewardActions} from './reward';
export type rootState = ReturnType<typeof reducer>;
export default configureStore({
reducer:reducer
});
const rootReducer = (state, action) => {
if (action.type === 'auth/logout') { // check for action type
state = undefined;
}
return reducer(state, action);
};
if i change this code with below one i got error mentioned.
import {combineReducers, configureStore} from '#reduxjs/toolkit';
import {menuReducer as menu} from './menu';
import {cartReducer as cart} from './shoppingCart';
import {optionsReducer as options} from './optionsItem';
import {homeReducer as home} from './home';
import {rewardReducer as reward} from './reward';
import {ordersReducer as orders} from './orders';
import {authReducer as auth} from './auth';
import giftCardReducer from '../store/giftCard';
import paymentMethodReducer from './paymentMethod';
import paymentToken from "./paymentToken";
import qRCode from "./qRCode";
import orderHistory from './orderHistory';
import orderDetail from './orderDetail';
import showCompletedOrder from './showCompletedOrder';
import paymentOptionsSummary from './paymentOptionsSummary';
import usersUpdate from './usersUpdate';
import referAFriend from './referAFriend';
import resetPassword from './resetPassword';
const reducer = combineReducers({
menu,
auth,
giftCardReducer,
paymentMethodReducer,
cart,
options,
orders,
home,
reward,
paymentToken,
qRCode,
orderHistory,
orderDetail,
showCompletedOrder,
paymentOptionsSummary,
usersUpdate,
referAFriend,
resetPassword
});
export {menuActions} from './menu';
export {cartActions} from './shoppingCart';
export {optionsActions} from './optionsItem';
export {ordersActions} from './orders';
export {authActions} from './auth';
export {homeActions} from './home';
export {rewardActions} from './reward';
export type rootState = ReturnType<typeof reducer>;
export default configureStore({
reducer:rootReducer
});
const rootReducer = (state, action) => {
if (action.type === 'auth/logout') { // check for action type
state = undefined;
}
return reducer(state, action);
};
Please help me.Thanks in advance.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
I also had this problem in React when I configured my redux store inside my client index.js file. This was my code that produces the error:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { configureStore } from "#reduxjs/toolkit";
import { Provider } from "react-redux";
import allReducers from "./redux/reducer";
const store = configureStore({ allReducers });
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
QUICK FIX: As the error suggests, "reducer" is a required argument... So, I just modified my store constant like so: configureStore({reducer: allReducers}). I just made "reducer" as a key, and passed allReducers as its value. My problem is then fixed.
Try this way
import { configureStore } from '#reduxjs/toolkit'
import { combineReducers } from 'redux'
const reducer = combineReducers({
// here we will be adding reducers
})
const store = configureStore({
reducer,
})
export default store;
Details Here
Actually I got the solution.
This error is shows because i have put the rootReducer function below the configure store that's why reducer id not getting the rootReducer function.
So, when I move it up then its working fine.
my solution was:
const rootReducer = combineReducers({
users: reducer
})
const store = createStore(rootReducer);
canceled braces and change configureStore to createStore
The documentation for configureStore neatly articulates the various options that can be passed in by keyword within the config object that a few of the others have alluded to.
If you are still struggling with this error, be sure to check the documentation here. It is very helpful.

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,
};

Store does not have a valid Reducer - How to pass a combined reducer into store?

I'm trying to get my head around Redux and other answers are making it more of an obstacle at this point.
reducers/index.js
import { combineReducers } from 'redux';
import photoInputPost from './photoInputPost'
import cameraInputPost from './cameraInputPost'
import textInputPost from './textInputPost'
export default rootReducer = combineReducers({
photoInputPost,
textInputPost,
cameraInputPost
})
store/index.js:
import { createStore } from 'redux'
import reducer from './../reducers/index'
export default Store = createStore(reducer)
One of the reducers, textInputPost.js
const textInputReducer = (initialState, action) => {
console.log('textInputReducer', action);
switch(action.type){
case 'ADD_INPUT_TEXT':
return { textInputValue: action.text };
default:
return state;
}
}
Not really sure what's going wrong but I'm probably passing the combined reducer in the wrong way.
You can create a rootReducer file as:
import { combineReducers } from "redux";
import reducer1 from "./reducer1";
import reducer2 from "./reducer2";
const rootReducer = combineReducers({ reducer1, reducer2 });
export default rootReducer;
...and in your index.js, add this rootReducer as:
import { createStore } from "redux";
import { Provider } from "react-redux";
import rootReducer from "./reducers/rootReducer";
import App from "./components/app";
import React from "react";
import ReactDom from "react-dom";
const store = createStore(rootReducer);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);

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 () )

React Native: Unable to use `store.dispatch` using redux-saga

I am using react-native 0.50.3 , I am trying to dispatch a navigation action but I get this error:
undefined is not an object (evaluating '_reducers2.default')
import configureStore from '../../../configureStore'
const store = configureStore(); <-- error points here
class childComp extends Component {
//...
goToProfile = () => {
store.dispatch(NavigationActions.navigate({routeName: 'Profile'}));
}
}
export default childComp;
configureStore.js:
import { createStore, applyMiddleware } from 'redux';
import app from './src/reducers';
import createSagaMiddleware from 'redux-saga';
import rootSaga from './sagas';
const sagaMiddleware = createSagaMiddleware()
export default function configureStore(){
const store = createStore(app, applyMiddleware(sagaMiddleware)) <-- also error points here
sagaMiddleware.run(rootSaga)
return store;
}
I have already used store.dispatch in index.js and it works fine.
Reducers
import { combineReducers } from 'redux';
import { TopLevelNavigator } from '../navigation/TopLevelNavigation/TopLevelConfig';
import { MainTabBar } from '../navigation/MainTabBar/MainTabBarConfig';
import { UserFormsTabBar } from '../navigation/UserFormsTabBar/UserFormsTabBarConfig';
import authReducer from './auth';
import employerReducer from './employer';
import contactReducer from './contact';
import personalReducer from './personal';
import bioReducer from './bio';
import saveFormsData from './saveData';
import saveAllFormsData from './saveFormsData';
import peopleReducer from './getPeople';
import currentUserReducer from './getCurrentUser';
const rootReducer = combineReducers({
TopLevelNavigationReducer: (state, action) => TopLevelNavigator.router.getStateForAction(action, state),
mainTabBarNavigationReducer: (state, action) => MainTabBar.router.getStateForAction(action, state),
userFormsTabBarNavigationReducer: (state, action) => UserFormsTabBar.router.getStateForAction(action, state),
authReducer,
employerReducer,
contactReducer,
personalReducer,
bioReducer,
saveFormsData,
saveAllFormsData,
peopleReducer,
currentUserReducer,
});
export default rootReducer;