score:1

Accepted answer

i would rather deconstruct the object and have a default object in the case of any data

// this could be even outside of your class.
const defaultobj = {
  firstname: '',
  familyname: '',
  address: 'enter your address',
  city: 'select your city',
  country: 'select your country',
  field: '',
}

/* the constructor*/

constructor(){
    const { userprofile = {} } = this.props.location.state || {};

    this.state = {
      ...defaultobj
      ...userprofile
    }
}

score:0

the "select your city" shouldn't be in your state. it's better to just leave it empty and pass it to the form as {state.city || "select your city"}

js:

if (this.props.location.state) {
const {firstname, familyname, address, country, field} = this.props.location.state.userprofile;

this.setstate({firstname, familyname, address, country, field, message = 'save my changes'})
}

jsx (view):

<p>city: {state.city || "select your city"}</p>
<p>message: {state.message || 'create'}</p>

score:1

at least a point that is possible to simplify: in location.state stores an object and the local state can be filled from it directly:

this.state = this.props.location.state 
  ? this.props.location.state.userprofile
  : {
    firstname'',
    familyname: '',
    address: 'enter your address',
    city: 'select your city',
    country: 'select your country',
    field: '',
  };

the message field looks like an unchangeable data, so it is better not to put it into the react state, but use a ternary operator in the render method


Related Query

More Query from same tag