So I have a DropDownPicker that I imported from react-native-dropdown-picker
,
I want to update a single item in a mapped state:
const [currentUser, setCurrentUser] = useState({Country: '', Name: ''});
The picker code is:
<DropDownPicker items={[ //JSON import
{label: 'USA'},
{label: 'India'},
{label: 'Germany'},
{label: 'France'},
{label: 'Israel'},
]}
placeholder="Country"
containerStyle={styles.pickerHeight}
style={styles.picker}
dropDownStyle={styles.pickerDrop}
onChangeItem = {(item) => {
// ------------------- here I want to update 'Country'
}}
/>
I've tried: setCurrentUser({Country: item.label})
but obviously it caused the Name
property to be deleted.
What is the correct way to update a single item in the state without losing data?
Thank you
You could use the spread operator to first get your current user's data, then simply overwrite the country: setCurrentUser(currentUser => ({ ...currentUser, Country: item.label }))