skip to Main Content

I am using useState hook to set a state variable. but there. was some strange behaviour.

CASE 1:

const [name, setName] = useState(route.params.name)

this is working fine have no problem.

CASE 2:

const [name] = useState(route.params.name)

this is also same.

CASE 3:

const name = useState(route.params.name)

Here is the confusion when I try to access the name it is crashing, when I console.log(name) the output was like this.

> [{"country_code": "US", "displayName": "Appleseed John",
> "facebook_profile_link": null, "filtered_contact_id": "23033489",
> "hasThumbnail": false, "internationalNumberFormat": "+1 888-555-5512",
> "key": "0undefined2", "mobile_number": "8885555512", "name":
> "Appleseed John", "nationalNumber": "8885555512", "social_id": null,
> "social_name": null, "social_picture_url": null, "social_url": null,
> "thumbnailPath": ""}, [Function bound dispatchSetState]]

I don’t know how to access the variables.

2

Answers


  1. The returned value is an array and the 0th index is the state itself and the 1st index is the function for setState.
    To access the values, use name[0] and to access the setState function, use name[1].
    But this is just against the naming conventions

    Login or Signup to reply.
  2. The case 3 you posted is also a valid expression as it is an array now which consists of two elements the first index 0 being the value itself and the second index 1 being the setState dispatcher. When using case 1 i.e.

    const [name, setName] = useState(route.params.name);
    

    you are destructuring the array. So all the above expressions are valid.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search