CodeYourFuture / syllabus-archive

[ARCHIVED] Please use https://github.com/CodeYourFuture/syllabus
https://codeyourfuture.github.io/syllabus-master
74 stars 115 forks source link

Convert React Forms section to use Hooks #430

Closed 40thieves closed 4 years ago

40thieves commented 4 years ago

Does exactly what it says on the tin.

Most of these changes I think are uncontroversial. However I wasn't sure exactly how to structure the state for the form with multiple fields. I ended up going for a single object:

const [userData, setUserData] = useState({
    username: "",
    email: "",
    password: ""
  });

But this means we have to use the object spread operator to update the state:

const updatedUserData = {
  ...userData,
  [event.target.name]: event.target.value
};

setUserData(updatedUserData);

I have included a section explaining the spread operator, but I have concerns that it might be a big leap for some students.

An alternative approach would be to abandon the dynamic object key idea and just use an if/switch:

if (event.target.name === "username") {
  setUsername(event.target.value)
} else if (event.target.name === "email") {
  setEmail(event.target.value)
} else if (event.target.name === "password") {
  setPassword(event.target.value)
}

What do you think?

Rendered version.

zubhav commented 4 years ago

I really think seperate useStates are the best approach for this. It will give students practice in managing multiple states, which is probably more common than managing a single object.

40thieves commented 4 years ago

I'm going to merge this as it is now (i.e. with the object spread) if there's strong objections we can change it later.

If we find that they really struggle with it, I think we can change tack and teach multiple states. Or possibly just mutating the object locally before setting that on state.