4

How I can serialize data in react ?

<form method="post" action="/insert" onSubmit={(e)=>this.addMysql(e)}>
    <label>Username</label>
    <input type="text" id="username" name="nameUser"/>
    <label>Password</label>
    <input type="text" id="password" name="passs"/>
    <button type="submit" type="submit">Dodaj</button>
</form>

This is my function

addMysql(event){
    console.log(event.targe) //this outputs an empty form
    event.preventDefault();
}

I dont want use State. Just onSubmit send all form data to AddMysql

https://medium.com/@snirlugassy/generic-input-handler-with-react-js-44a97e22cd0d

Thanks Sag1v

Paweł Baca
  • 814
  • 2
  • 15
  • 28

2 Answers2

1

I suggest you use states because that is the Reacty way. if not, I may suggest a few things.

Normally I would have suggested to use FormData API, but it is not supported by IE and older browsers.

I think this answer should get you going, because its a plain JS version of serialize.

Finnally serialize if you're using jQuery, which I think you're not or you're not supposed to.

Minato
  • 4,383
  • 1
  • 22
  • 28
-1
//So, here's a simple trick i use to get this done:
//Using React Hook

    

const [data, setData] = useState({});
//the create an onInputChange function for the Inputs this way
const onInputChange = async e =>{
  const {name, value} = e.target;
  //check to validate if entry is not a number
  if(isNaN(name)){
    data[name] = value;
    
    //somehow update data
    setData({...data})
  }
}
Vicheans
  • 65
  • 1
  • 5