React Native + Redux Tool kit + AsyncStorage
--
3 steps to add redux with a redux toolkit and async storage in a react-native application
Under the Hood
The story begins when I am developing a non-custodial wallet app and web3 mobile app using react-native.
Once the user creates an account or wallet he/she can view all the wallets and addresses and check the balance.
After creating an account I want to store wallets and async storage as we will not be saving wallets in the database.
Tech Stack
And since I am using react-native so redux will be the state management.
But redux now provides the latest or upgrade way to write actions and reducers called slice, so I’ll be using slice.
- React
- React Native
- Redux Toolkit
- Redux Persist
- AsyncStorage
Redux persists helps to persist the reducer states and for that, it uses async storage in react-native just like local storage in react
Installing Packages
- react
- react-native
- react-redux
- redux-persists
- @react-native-async-storage/async-storage
Creating Reducer
The Redux toolkit now provides an easy way to write reducers and actions in the same method.
Below is the code
import {createSlice} from '@reduxjs/toolkit';
const initialState = {
wallet: [
{
walletAddress: 'zxcvbnm',
balance: 100,
},
{
walletAddress: 'asdfghjkl',
balance: 300,
},
{
walletAddress: 'qwertyuiop',
balance: 400,
},
],
activeWallet: null,
};
const walletSlice = createSlice({
name: 'userWallet',
initialState,
reducers: {
addWallet: (state, action) => {
return {...state, wallet: action.payload};
},
addActiveWallet: (state, action) => {
return {...state, activeWallet: action.payload};
},
},
});
export const {addWallet, addActiveWallet} = walletSlice.actions;
export const reducer = walletSlice.reducer;