Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

Unable to save value to AsyncStorage, Redux Persist and React Native

I am working with redux-persist and am trying to save a value (text) to AsyncStorage, but it is not working. I've confirmed with the debugger that the value isn't updating in AsyncStorage and can also confirm that the value is being updated in the store correctly and REHYDRATE is working correctly.

reducer:

import {SET_TEXT} from '../types/types'
import { REHYDRATE } from 'redux-persist';
import { persistReducer } from 'redux-persist'
import AsyncStorage from '@react-native-community/async-storage';

const INITIAL_STATE = {
    text: 'hi'
}

const persistConfig = {
    key: 'pref',
    storage: AsyncStorage,
    keyPrefix: ''
  }

const prefScreen = (state = INITIAL_STATE, action ) => {
    switch(action.type){
        case REHYDRATE:
            console.log(action.payload)
            return { ...state, text: action.payload.text}
        case SET_TEXT:
            return { ...state, text: action.payload};
        default:
            return state;
    }
}

export default persistReducer(persistConfig,prefScreen);

combined reducers:

import {combineReducers} from 'redux';
import prefScreen from './PrefScreen_reducer';

const reducers = combineReducers({
    pref: prefScreen
});

export default reducers;

store:

import { createStore, applyMiddleware, compose } from 'redux';
import reducers from './reducers';
import thunkMiddleware from 'redux-thunk'
import { persistReducer } from 'redux-persist'
import AsyncStorage from '@react-native-community/async-storage';
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';

export default function configStore() {
  const persistConfig = {
    key: 'root',
    storage: AsyncStorage,
    stateReconciler: autoMergeLevel2
  }

  const composeEnhanser = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; 

  const persistedReducer = persistReducer(persistConfig, reducers)

  const store = createStore(
    persistedReducer,
    composeEnhanser(applyMiddleware(thunkMiddleware)) 
  );

  return store  
};

persistor:

import configStore from './store'
import { persistStore } from 'redux-persist'

export default function makePeristor() {
    const store = configStore()
    const persistor = persistStore(store)
    return persistor
}
question from:https://stackoverflow.com/questions/66050450/unable-to-save-value-to-asyncstorage-redux-persist-and-react-native

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...