-3

Somewhere in the code lies a flaw if someone could spot it it I would appreciate help thank you.

Step 1. react form to add a record to the state containing two variables [email & name]

    export const AddForm = (props) => {

         const [ name, setName ] = useState('')
         const [ email, setEmail ] = useState('');

         return (
              <div>
                    Name:
                   <input type="text" 
                           id="name" 
                           onChange={ (event)=> { setName(event.target.value) }} /><br />
                   Email:
                   <input type="email" 
                           id="email" 
                           onChange={ (event)=> { setEmail(event.target.value) }}/><br />
                   <button type="button" 
                           onClick={ ()=> { props.doAdd(name,email) } } >Add</button>
              </div>
         )

    }

Step 2. The execution of the doAdd() function inside the main app.js

  const doAdd = (name,email) => {
    var newData = '{"name":'+name+',"email":'+email+'}';
    setAllVals([...allVals,newData]);

  }

after entering values my array of objects does not perform properly. for example allVals[0].name = blank (it should be name1)

here is console.log enter image description here

Nelles
  • 3,565
  • 6
  • 26
  • 39

1 Answers1

-1

Use this

const doAdd = (n,e) => {
    var newData = {name:n,email:e};
    setAllVals([...allVals,newData]);
  }

pass n to name-> name:n and e to email-> email:e. here your name and email is key of object and n,e are values.

It's similar to

var objExample = {
    key1: value1,
    key2: value2
};

you can check for better understanding Objects

akhtarvahid
  • 6,733
  • 2
  • 14
  • 21
  • @Nelles your welcome... if answer is helpful for you please accept/vote for this. – akhtarvahid Jan 24 '20 at 16:23
  • 3
    @Nelles Because the fact that `newData` is a string and not an object should have been easy to find with some basic debugging. – Andreas Jan 24 '20 at 16:31
  • @Andreas truthfully you are correct - it was not throwing an error and I was trapped on it for a long time. I apologise. – Nelles Jan 24 '20 at 16:35
  • 3
    This isn't a very good answer... It gives no explanation as to why the error happens, or what your code does to address it. And it unnecessarily changes the parameter names of the OP's function to be completely meaningless single letters. – Brian Thompson Jan 24 '20 at 16:44