In my application, the user should have the possibility to edit his name. I thought about having his initial name as the default value of useState()
. This works perfectly - the name is also updated as well.
function EditName(props) {
const { navigation, dispatch, initFirstName } = props;
const [text, setText] = useState(initFirstName);
return (
<>
<Button title="Save" onPress={() => dispatch(updateFirstName(text))} />
<TextInput
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
onChangeText={(inp) => setText(inp)}
value={text}
/>
</>
)
}
function mapStateToProps(state) {
return (
{
initFirstName: state.user.data.firstName,
}
);
}
export default connect(mapStateToProps)(EditName);
But now I came across a problem if the user clicks on the save button and dispatch(updateFirstName(text))
is handled. text
is overwriten by initFirstName
again.
My Redux (toolkit) store is structured as follows:
{
data: {
firstName: "Test"
},
updateFirstName: {
pending: null,
error: null,
},
}
The updateFirstName(text)
method dispatches an action that sets state.updateFirstName.pending = true;
. If I leave this out - everything works.
So I guess that a new reference to the store (state) is created and React thinks: "Oh - I got a new initFirstName" (beside it's still the same because the update hasn't happened yet).
What would be a better way to do this? What's a solution for this problem?
question from:
https://stackoverflow.com/questions/65870537/redux-store-updates-everything-even-if-i-just-update-a-nested-attribute 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…