Access data from store in App.js. - Redux Persist

1.8k views Asked by At

i am stuck with this Problem. Any help would be appreciated.

I am using Redux Persist in my react native app and i want to access data stored in state 'number' from store.js in App.js.

I have pasted my code below.

Here is my actions.js


export const setNumber = number => dispatch => {
  dispatch({
    type: SET_NUMBER,
    payload: number,
  });
};

reducers.js

import {SET_NUMBER} from './actions';

const initialState = {
  number: [],
};

function numberReducer(state = initialState, action) {
  switch (action.type) {
    case SET_NUMBER:
      return {...state, number: action.payload};
    default:
      return state;
  }
}

export default numberReducer;

store.js

import {createStore, combineReducers, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {persistStore, persistReducer} from 'redux-persist';

import numberReducer from './reducers';

const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
  whitelist: ['number'],
};

const rootReducer = combineReducers({
  numberReducer: persistReducer(persistConfig, numberReducer),
});

const store = createStore(rootReducer, applyMiddleware(thunk));
const persistor = persistStore(store);

export {store, persistor};

App.js

import React, {Component} from 'react';
import {View, Text, SafeAreaView, Button} from 'react-native';
import {NavigationContainer} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import {Provider} from 'react-redux';
import {store, persistor} from './redux/store';
import {PersistGate} from 'redux-persist/integration/react';
import {connect} from 'react-redux';

import Login from './screens/Login';
import Home from './screens/Home';
import Details from './screens/Details';

const Stack = createNativeStackNavigator();

function App() {
  if (number == null) {
    return (
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen
            name="Home"
            component={Home}
            options={{
              headerStyle: {
                backgroundColor: 'lightblue',
              },
            }}
          />
        </Stack.Navigator>
      </NavigationContainer>
    );
  } else {
    return (
      <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
          <NavigationContainer>
            <Stack.Navigator>
              <Stack.Screen
                name="Login"
                component={Login}
                options={{
                  headerStyle: {
                    backgroundColor: 'lightblue',
                  },
                }}
              />
              <Stack.Screen
                name="Home"
                component={Home}
                options={{
                  headerStyle: {
                    backgroundColor: 'lightblue',
                  },
                }}
              />
              <Stack.Screen
                name="Details"
                component={Details}
                options={{
                  headerStyle: {
                    backgroundColor: 'lightblue',
                  },
                }}
              />
            </Stack.Navigator>
          </NavigationContainer>
        </PersistGate>
      </Provider>
    );
  }
}

export default App;

I want to access the data in 'number' so that my 'if condition' would work in App.js Right now it says variable 'number' can not be found which is understandable. Is there any way that i can access data in 'number' for if condition to work. Thanks in advance.

2

There are 2 answers

0
Kartik Malik On

You can directly access the state from your store like so

store.getState().number

But, it is not advisable to access the store directly like that.

Note that redux specifically advise against trying to import and use the store into other files in the codebase unless absolutely necessary.

refer this: https://redux.js.org/style-guide/style-guide#only-one-redux-store-per-app

1
Maxwell On

You're looking for the 'useSelector' hook from react-redux. You'd implement it like this.

const num = useSelector(state => state.numberReducer.number)

The problem here though is that it wouldn't work because it's not inside the Provider/store. You'll need to do a small rework of the conditional statement you have there in order to ensure that you have access to the store.

<Provider store={store}
  <PersistGate loading={null} persistor={persistor}>
    <NavigationContainer>

    --- 
     do your conditional stuff here, but in another file. use the 
     useSelector there. ideally put the conditional in the prop 
     'initialRouteName' as I mentioned in a comment below
    ---

    </NavigationContainer>
  </PersisGate>
</Provider>