'How to update a value with reducer via text input?
I would like to update the value of a variable in the reducer. In the app the user can type the username in a text input field in one screen. The reducer should update this state so that I can output it on a different screen. Right now I'm using useState but I'd like to use the reducer instead. I'm new to coding and I'm really struggling with this so I hope someone can help me.
The reducer:
import { createSlice } from '@reduxjs/toolkit';
const userSlice = createSlice({
name: 'user',
initialState: " ",
reducers: {
setUser: (state = initialState, action) => {
???
},
}
});
export const {setUser} = userSlice.actions;
export default userSlice.reducer;
Code in the screen with useState:
const [user, setUser] = useState("");
const [userName, setUserName] = useState("");
const onValueChange = (number) => setUser(number);
const onButtonHandler = () => setUserName(user);
<View style= {globalStyles.containerInput}>
<TextInput
style= {globalStyles.input}
maxLength={20}
minLegth={10}
keyboardType="number-pad"
value={user}
onChangeText={onValueChange}
/>
</View>
<View style= {globalStyles.containerButton}>
<Pressable
style={globalStyles.button}
onPress={onButtonHandler}
>
</Pressable>
</View>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
