I am using Redux Persist in my react native app. My app is a money manager so the user can store expenses and incomes. Therefore I want to have an array called allEntries where all the entries (expense or income) are stored.
My EntriesOverview class where all the entries are shown. I am adding a random new entry in the goToAddNewEntryScreen() methode for demonstration purpose.
import React from 'react';
import {ColorPalette} from '../../Assets/Colors/ColorPalette';
import {Dimensions, Image, StyleSheet, Text, TouchableHighlight, View} from 'react-native';
import {addEntry} from '../../Redux/Actions/counterActions';
import {connect} from 'react-redux';
class EntriesOverviewScreen extends React.Component {
state: {};
styles = StyleSheet.create({
btn_add: {
position: 'absolute',
right: 10,
bottom: 10,
backgroundColor: ColorPalette.lightMode.primary,
color: ColorPalette.lightMode.white,
borderRadius: Math.round(Dimensions.get('window').width + Dimensions.get('window').height) / 2,
width: Dimensions.get('window').width * 0.15,
height: Dimensions.get('window').width * 0.15,
justifyContent: 'center',
alignItems: 'center',
},
btn_add_icon: {
width: '50%',
height: '50%',
},
background_entries_overview: {
backgroundColor: ColorPalette.lightMode.white,
height: '100%',
},
});
constructor(props: Props) {
super(props);
this.state = {};
}
render() {
return (
<View style={this.styles.background_entries_overview}>
<Text>Entries overview</Text>
<Text>{JSON.stringify(this.props.allEntries)}</Text>
<TouchableHighlight
style={this.styles.btn_add}
onPress={() => this.goToAddNewEntryScreen()}>
<Image style={this.styles.btn_add_icon}
source={require('../../../MoneyMaster/Assets/Icons/plus_white.png')}/>
</TouchableHighlight>
</View>
);
}
goToAddNewEntryScreen() {
this.props.reduxAddEntry({
id: -1,
isExpense: true,
amount: 0,
date: new Date('2000-11-25'),
note: '',
reoccurring: 'asdf',
categoryId: 0,
});
this.props.navigation.navigate('AddEntryScreen');
}
}
// Map State To Props (Redux Store Passes State To Component)
const mapStateToProps = (state) => {
// Redux Store --> Component
return {
allEntries: state.entriesReducer.allEntries,
};
};
// Map Dispatch To Props (Dispatch Actions To Reducers. Reducers Then Modify The Data And Assign It To Your Props)
const mapDispatchToProps = (dispatch) => {
// Action
return {
// Increase Counter
reduxAddEntry: (entryToAdd) => dispatch(addEntry(entryToAdd)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(EntriesOverviewScreen);
My counterAction class
// Add an Entry
export const addEntry = (entryToAdd) => ({
type: 'ADD_ENTRY',
entryToAdd: entryToAdd
});
My entriesReducer class
// Initial State
const initialState = {
allEntries:[],
};
// Reducers (Modifies The State And Returns A New State)
const entriesReducer = (state = initialState, action) => {
switch (action.type) {
// Increase Counter
case 'ADD_ENTRY': {
let updatedAllEntries=state.allEntries.push(action.entryToAdd);
return {
// State
...state,
// Redux Store
allEntries: updatedAllEntries,
}
}
// Default
default: {
return state;
}
}
};
// Exports
export default entriesReducer;
The strange thing for me is that when I debug it and start the app for the first time the state.allEntries value in my entriesReducer is always 1 eventhough it should be an empty array. Therefore I cant add the entry via the .push methode.Didn't I set the state to an empty array in the entriesReducer? (See image)Initial value is 1 instead of []
Do you have any idea how it could be fixed? Thanks for your help :) And don't be to harsh I am using it the first time ;)
The store
// Imports: Dependencies
import AsyncStorage from '@react-native-async-storage/async-storage';
import {applyMiddleware, createStore} from 'redux';
import {createLogger} from 'redux-logger';
import {persistReducer, persistStore} from 'redux-persist';
// Imports: Redux
import rootReducer from '../Reducers/index';
// Middleware: Redux Persist Config
const persistConfig = {
// Root?
key: 'root',
// Storage Method (React Native)
storage: AsyncStorage,
// Whitelist (Save Specific Reducers)
whitelist: [
'entriesReducer',
],
// Blacklist (Don't Save Specific Reducers)
blacklist: [],
};
// Middleware: Redux Persist Persisted Reducer
const persistedReducer = persistReducer(persistConfig, rootReducer);
// Redux: Store
const store = createStore(
persistedReducer,
applyMiddleware(
createLogger(),
),
);
// Middleware: Redux Persist Persister
let persistor = persistStore(store);
// Exports
export {
store,
persistor,
};
The index
// Imports: Dependencies
import { combineReducers } from 'redux';
// Imports: Reducers
import entriesReducer from './entriesReducer';
// Redux: Root Reducer
const rootReducer = combineReducers({
entriesReducer: entriesReducer,
});
// Exports
export default rootReducer;