0

I want to save a few details of the state value to firestore. How can I achieve this?

state = {
    sp_Name: '',
    sp_Phone: '',
    sp_email: '',
    sp_Role: 'Fleet Provider',
    usr_org_LicenseNumber: '',
    sp_License:'',
    usr_org_StateConvered: '',
    usr_org_DistConvered: '',
    EquipmentCount: 0,
    loading:false,
    checked: false,
    disChecked : false,
    open: false,
    message:'',
    sp_NameError: '',
    sp_PhoneError: '',
    sp_emailError: '',
    usr_org_LicenseNumberError: '',
    sp_LicenseError:'',
    usr_org_StateConveredError: '',
    usr_org_DistConveredError: '',
    sp_NumberofEquipmentsError:'',
};

I'm deleting some of the details, but is there any other way to delete all at once.

const stateObj = this.state;
delete stateObj['loading'];
delete stateObj['checked'];
delete stateObj['disChecked'];
delete stateObj['open'];
delete stateObj['message'];
delete stateObj['sp_NameError','sp_PhoneError','sp_emailError'];
delete stateObj['usr_org_LicenseNumberError', 'sp_LicenseError','usr_org_StateConveredError',
'usr_org_DistConveredError','sp_NumberofEquipmentsError'];
this.props.UpdateUserDetails(uid, stateObj)
this.openSnackbar({ message: 'Submitted Successfully.!' });
Patrick
  • 1,728
  • 2
  • 17
  • 30
ansh
  • 115
  • 2
  • 14
  • 3
    Possible duplicate of [How can I remove an attribute from a Reactjs component's state object](https://stackoverflow.com/questions/32884780/how-can-i-remove-an-attribute-from-a-reactjs-components-state-object) – minus.273 Jun 13 '19 at 06:32

2 Answers2

0

You can use a combination of Object.entries and array.reduce, which should make this a bit cleaner:

You just need an array that contains the keys you no longer need:

let keysToRemove = ["loading", "checked", "disChecked", "open", "message", "sp_NameError", "sp_PhoneError", "sp_emailError", 'usr_org_LicenseNumberError', 'sp_LicenseError','usr_org_StateConveredError','usr_org_DistConveredError','sp_NumberofEquipmentsError']

and a new state

let newState = Object.entries({...state}).reduce((obj, [key, value]) => {
    if(!keysToRemove.includes(key)){
        obj[key] = value
    }
    return obj
}, {})

this.props.UpdateUserDetails(uid, newState)
Chris Ngo
  • 15,460
  • 3
  • 23
  • 46
0

Try this one.

keysToBeRemoved = ["loading", "checked", "disChecked", "open", "message"];
this.setState(prevState => ({
  ...Object.keys(prevState).filter(item => !keysToBeRemoved.includes(item)
    ).map(field => ({
      [field]: prevState[field]}
    ))
}))
Ken Labso
  • 885
  • 9
  • 13