FAQ: The State Hook - Objects in State

This community-built FAQ covers the “Objects in State” exercise from the lesson “The State Hook”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn React

FAQs on the exercise Objects in State

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Learn more about how to use this guide.

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

“Did you notice the square brackets around the name ? This Computed Property Name allows us to use the string value stored by the name variable as a property key!”

I don’t really understand this. What kind of datatype is name?

1 Like

The datatype of name is string. If you look at the input elements, they have an attribute called name (i.e. name="firstName", name="password"). The “firstName” and “password” are strings. The Computed Property Name notation allows us to use these strings as keys in our state object.
In the snippet

{ ...prev, 
[name]: value }

the string name “firstName” or “password” will be converted to property keys in our state object because of the square brackets around name. So, our object will have property keys called firstName and password. The value of the property will be whatever we have entered in the respective input field.
For example, if we enter Jack in the input field for First Name, then the [name]: value notation will mean that the object has a property whose key is firstName and value is “Jack”. If we did something like console.log(formState.firstName), it will output the string value Jack to the console.

1 Like
setFormState((prev) => ({ ...prev }))

Why do we use parentheses to surround the object? Is it to indicate that the object between it is to be returned? I’ve tried the same method in the previous exercise on return [item, ...prev], changing it into ([item, ...prev]), and it worked. But I just want to be sure if that is the case.

3 Likes

I didn’t think the parentheses in this snippet were significant until you posted your comment. Researching and thinking about the topic, the parentheses are indeed necessary in the snippet you posted. It has to do with the implicit return of an object in an arrow function.
If we wanted to explicitly return an object in an arrow function, we would have to use the return keyword and use curly braces:

setFormState((prev) => {
  return {...prev};
})

However, we want to do an implicit return of the object. If we tried to do something like:

setFormState((prev) => {...prev})

this wouldn’t capture our intent. We intend to implicitly return the {...prev} object, but JavaScript looks at the curly braces and decides that this is actually a block of code and not an object.
To implicitly return the object, we need the parentheses as you posted above:

setFormState((prev) => ({...prev}))

Have a look at this article. It is a short read, but it explains the issue very nicely with examples.

As regards the previous exercise, we are returning a list explicitly. Furthermore, the return keyword and the opening bracket of the list are on the same line. So, we don’t need parentheses.
return [item, ...prev]; does the job just fine.

3 Likes

Hi,

I can’t understand why do we need this braces (marked in arrows)? Is there an other way? Thanks!

setProfile((prevProfile) => → ( <–{
…prevProfile,
[name]: value
} → ) <–);

 const handleChange = ({ target }) => {
    const {name, value} = target
    setProfile((prevProfile) => ({
      ...prevProfile,
      [name]: value
      }));
  };

Have you looked at the previous post? It is the same reason about the implicit return of an object in an arrow function.
In the arrow function in setProfile, we want to return the object { ...prevProfile, [name]: value }

If you want to do an explicit return, you could do something like:

    setProfile((prevProfile) => {
        return { ...prevProfile, [name]: value };
    });

However, if we want to do an implicit return, then

    setProfile((prevProfile) => { ...prevProfile, [name]: value } );

will NOT work. We want to implicitly return the object, but the compiler will think that the curly braces { } aren’t meant to denote an object but a block of code constituting the body of the arrow function.
If we want to do the implicit return of the object, we need the parentheses:

    setProfile((prevProfile) => ( { ...prevProfile, [name]: value } ) );
5 Likes
    value={profile.password ||  ' '}   

can anyone tell me why we use or operator with single ’ ’ ?

I guess it might mean that this input field could also be left blank (as a string)?

I am confused as to how the state is stored.
Are there 4 different profile objects, each with a key:value pair? Or is profile just one large object holding 4 key:value pairs?

The latter case.

profile is one object and is initially an empty object. As we type into one of the fields, the handleChange event handler comes into play and the setProfile state setter updates the state.

In the state setter, the spread syntax ...prevProfile copies all the key value pairs in the existing profile.

[name]: value then creates a new entry in the object. If a key doesn’t exist in the profile, then this will create a new key value pair in the object. If the key-value already exists in the object, then it will overwrite that value. This is why the syntax is

{
  ...prevProfile,
  [name]: value
}

If we reversed the order,

{
  [name]: value,
  ...prevProfile
}

then it wouldn’t work as intended, because this snippet will first create our key-value pair and then copy all the existing key-value pairs from the previous profile object. If the previous profile object already has the same key as the new key-value pair, then the previous key-value pair will overwrite our new key-value pair.

Perhaps, this example will make things more clear.

const oldObj = {
  firstNum: 43,
  secondNum: 66
};

console.log(oldObj);

const newObj = {
  ...oldObj,
  firstNum: 60
}

console.log(newObj);

// Output:
// { firstNum: 43, secondNum: 66 }
//  { firstNum: 60, secondNum: 66 }

versus

const oldObj = {
  firstNum: 43,
  secondNum: 66
};

console.log(oldObj);

const newObj = {
  firstNum: 60,
  ...oldObj
}

console.log(newObj);

// Output:
// { firstNum: 43, secondNum: 66 }
//  { firstNum: 43, secondNum: 66 }
1 Like

I used google developer tools to investigate the event handler and confused as to what exactly is going on in that function:

As per the screenshot, when you go into the setProfile function, isn’t there supposed to be a prevProfile value as a variable? (there’s nothing regarding prevProfile in the scope)

Also, as shown, the values for firstname and lastname is already determined even before running the entirety of the code (including the return function at the bottom):

profile = {firstName: ‘f’, lastName: ‘h’}
already assigned

confused.