cancan
cancan

Reputation: 131

how can i save/store data in react native, redux? and call it afterwards

I am working on a react native project and I want to save my data like name or an email adress and reach it afterwards. of course there will be multiple data. I searched it and basically the first option is AsyncStorage (https://facebook.github.io/react-native/docs/asyncstorage.html). I sort of understood this but I didnt get how to store multiple names or emails.. Also, I want to use redux for storage, if possible. I also searched for it but i couldnt find a satisfying way to implement it. Moreover, there is redux-persist library. I think this library looks the best, but I am not sure if i need it or not. I cannot decide which way to start and move on. Any suggesstions or experience on it? And after saving, how to call the data??

Upvotes: 2

Views: 3583

Answers (2)

sazedul
sazedul

Reputation: 46

I found redux-storage Library easier to implement for react-native redux-storage to save state of redux. To use engine for react-native you need to use redux-storage-engine-reactnativeasyncstorage.

Following is my code

import { createStore, applyMiddleware, combineReducers } from 'redux';
import rootReducer from './reducers'; 
import logger from 'redux-logger';
import * as storage from 'redux-storage'

import createEngine from 'redux-storage-engine-reactnativeasyncstorage';
const engine = createEngine('my-save-key');

export default function configureStore() {
    const reducer = storage.reducer(rootReducer);

    const middleware = storage.createMiddleware(engine);

    const createStoreWithMiddleware = applyMiddleware(middleware)(createStore);
    const store = createStoreWithMiddleware(reducer, applyMiddleware(logger));

    const load = storage.createLoader(engine);
    load(store);


    return store;
}

Hope that might help others too in present time.

Thanks

Upvotes: 0

Tom Walters
Tom Walters

Reputation: 15616

The redux-persist library is excellent and is backed by the AsyncStorage mechanism included with React Native. The library allows you to save the current state of your Redux store and will automatically rehydrate it when the app is next launched.

The library also allows you to implement custom logic when rehydrating for greater control of the process. Generally speaking AsyncStorage shouldn't be directly used to save raw-data, but have an abstraction layer over the top - Redux Persist is a good abstraction if you're already using Redux.

Upvotes: 2

Related Questions