0

Object dot-notation does not work here as value is undefined

<Input key={i} value={inputs.e} name={e} onNameChange={handleChange} />

this works

<Input key={i} value={inputs[e]} name={e} onNameChange={handleChange} />

this is signifying to me that initializing state like this may not be the best idea?

function _Login() {
  const inputNames = ["firstName", "lastName"];
  const [inputs, setInputs] = React.useState(
    inputNames
      .map((e) => ({ [e]: "" }))
      .reduce((accumulator, current) => ({ ...accumulator, ...current }), {})
  );
  const handleChange = (value: object) => setInputs({ ...inputs, ...value });

  return (
    <form>
      {inputNames.map((e, i) => (
        <Input key={i} value={inputs[e]} name={e} onNameChange={handleChange} />
      ))}
    </form>
  );
}

the reduce is just reducing an array of objects to one object

What is a good explanation for all of this?

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
  • Edit your question and convert your code sample into an interactive snippet. [How?](https://meta.stackoverflow.com/questions/338537/how-do-i-create-a-react-stack-snippet-with-jsx-support) – Janez Kuhar Apr 05 '21 at 20:07
  • You are correct @JanezKuhar, thank you! It was a duplicate as I was trying to use dot notation to access a property name that is stored in a variable, which needs bracket notation. – William Schamovic Apr 05 '21 at 21:00
  • Ah, then thank @PatrickRoberts and others ([revision history](https://stackoverflow.com/posts/66959080/revisions)). ^^ – Janez Kuhar Apr 05 '21 at 21:07
  • @JanezKuhar thank you for helping me with the revision history, and yes I will thank him! – William Schamovic Apr 05 '21 at 22:22
  • @PatrickRoberts thank you for your help as it is duplicate! – William Schamovic Apr 05 '21 at 22:24

0 Answers0