Search code examples
react-nativereact-contextreact-native-state

Setting Object State in Context


I am new to React and React Native and am trying to understand some things. I am hoping someone can explain to me what I am doing wrong here. I have an object that I am attempting to set the value of independent variables with onChangeText. That object handles the data through

const { data, updateUserDetails} = useContext(MembershipContext);

In the form field

<TextInput
    style={styles.inputStyle}
    placeholder="First Name"
    value={data.userDetails.fname}
    onChangeText={(val) => updateUserDetails('fname', val)}
/>

And in the Context file

const updateUserDetails = (field, val) => {
    setUserDetails([
        ...userDetails.field, val
    ]);
};

I am trying to update this state

const [userDetails, setUserDetails] = useState({
    fname: '',
    lname: '',
    address: '',
    city: '',
    state: '',
    zip: '',
    email: '',
    phone: '',
    password: '',
});

I hope that this is enough to analyze. Any help would be appreciated


Solution

  • Ciao, I think your problem is on how you call setUserDetails. Try to replace it with:

    const updateUserDetails = (field, val) => {
        setUserDetails({
            ...userDetails, [field]: val
        });
    };
    

    And problem should be solved.