Home > database >  redux persist data not shown react native
redux persist data not shown react native

Time:11-25

i am using redux persits in my react native application and below is my code

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 authReducer from './reducer';

const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
};

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

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

action.js

// Define action types
 export const CREATE_USER = 'CREATE_USER';
 export const INTRO_DONE = 'INTRO_DONE';
 export const VERIFY_USER = 'VERIFY_USER';
 export const GET_ACCESS_TOKEN = 'GET_ACCESS_TOKEN';

 export const createUser = users => dispatch => {
  dispatch({
   type: CREATE_USER,
    payload: users,
 });

};

export const getAccessToken = access_token => dispatch => {
 dispatch({
 type: GET_ACCESS_TOKEN,
 payload: access_token,
});
};

reducer.js

import {CREATE_USER, GET_ACCESS_TOKEN, INTRO_DONE, VERIFY_USER} from './action';

 const initialState = {
  users: {},
  access_token: '',
 };

  function authReducer(state = initialState, action) {
switch (action.type) {
 case CREATE_USER:
  return {...state, users: action.payload};
case GET_ACCESS_TOKEN:
  return {...state, access_token: action.payload};
 default:
  return state;
  }
 }

 export default authReducer;

I store data like this

const dispatch = useDispatch();
dispatch({
type: CREATE_USER,
user: response.data,
})

dispatch({
type: GET_ACCESS_TOKEN,
user: response.data.data.access_token,
})

When i try to log reducer file data store in access_token but when i get access_token from below code getting undefind

const {access_token, users} = useSelector(state => state.authReducer);

users data is printed but access_token getting undefind from above code , Any idea how can i solve this ?

CodePudding user response:

I think the way your dispatching your action creator is incorrect.

Your doing like this

dispatch({
  type: GET_ACCESS_TOKEN,
  user: response.data.data.access_token,
})

I think it should be like this.

dispatch({
      type: GET_ACCESS_TOKEN,
      payload: response.data.data.access_token,
    });
  • Related