I have just for several reasons migrated from the old style of redux (pre 2019) which used case, switch etc. The redux store gets updated as it should which i can see in the TextInput for example but when trying to use the selected value from redux store elsewhere inside the screen function it seems to initial state and not the updated one. Shortened code below and any help would be greatly appriciated.
redux/slices/auth.js
import { createSlice } from "@reduxjs/toolkit"
const initialState = {
email: "",
}
const authSlice = createSlice({
name: 'userAuth',
initialState,
reducers: {
setEmail: (state, action) => {
state.email = action.payload.email;
}
}
});
export const { setEmail } = authSlice.actions;
export const selectEmail = (state) => state.userAuth.email;
export default authSlice.reducer;
redux/store.js
import { configureStore } from '@reduxjs/toolkit'
import authSlice from './slices/auth'
export const store = configureStore({
reducer: {
userAuth: authSlice,
},
})
screens/LoginScreen.js
import {useSelector, useDispatch} from 'react-redux';
import { selectEmail, setEmail } from '../../redux/slices/auth';
function LoginScreen({navigation}) {
const _email = useSelector(selectEmail);
const onEmailButtonPress = async () => {
console.log("Begin sign in: Email");
// GETS INITIAL STATE AND NOT UPDATED ONE
if (_email == null || _email == 0 || _email == ""){
console.log(_email);
return;
}
}
return (
<View>
<Text>Login with e-mail</Text>
<TextInput
placeholder="Enter e-mail address"
placeholderTextColor={'#000'}
keyboardType="email-address"
onChangeText={(value) => dispatch(setEmail(value))}
maxLength={128}
value={_email} // SHOWS UPDATED STATE
/>
<TouchableOpacity
onPress={() => onEmailButtonPress()}
>
<Text>Continue</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
});
export default LoginScreen;
App.js
class App extends React.Component {
render() {
LogBox.ignoreAllLogs(true);
return (
<Provider store={store}>
{/*<PersistGate persistor={persistor}>*/}
<LoadingScreen />
{/*</PersistGate>*/}
</Provider>
);
}
}
CodePudding user response:
In the reducer you are reading action.payload.email
but in the component you are dispatching setEmail(value)
.
That's not consistent, or you read in the reducer action.payload
or you dispatch in the component setEmail({email: value})