Reputation: 391
Posting a React form is typically straightforward. However, I need to customize the payload before sending it to this particular endpoint. I need it to look like this:
{
"httpMethod": "POST",
"body": {
"TableName": "Users",
"Item": {
"email": "[email protected]",
"first_name": "Sasquatch",
"last_name": "Bigfoot"
}
}
This is what I have now, but the format isn't correct:
const CreateUser = () => {
const [user, setUser] = useState({
'httpMethod': 'POST',
'body': {
'TableName' : 'Users',
'Item' : {
email: '', first_name: '', last_name: ''
}
}
});
const handleChange = (event) => {
setUser({...user, [event.target.name]: event.target.value})
}
const url = 'https://aaaaaaa.execute-api.us-east-1.amazonaws.com/dev/';
const handleSubmit = (e) => {
e.preventDefault()
axios.post(url, user)
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
}
return (
<div className="container">
<form className='white' onSubmit={handleSubmit}>
<h5 className="grey-text.text-darken-3">Create User</h5>
<div className="input-field">
<label htmlFor="email">Email</label>
<input type="text" name="email" value={setUser.email} onChange={handleChange} required />
</div>
<div className="input-field">
<label htmlFor="first_name">First Name</label>
<input type="text" name="first_name" value={setUser.first_name} onChange={handleChange} required />
</div>
<div className="input-field">
<label htmlFor="last_name">Last Name</label>
<input type="text" name="last_name" value={setUser.last_name} onChange={handleChange} required />
</div>
<div className="input-field">
<button className="btn blue darken-3" type="submit">Sign Up</button>
</div>
</form>
</div>
);
}
When I find the data in the debugger it looks like this:
{
"httpMethod":"POST",
"body": {
"TableName":"Users",
"Item": {
“email":"",
"first_name":"",
"last_name":""
}
},
"email":"[email protected]",
"first_name":"Sasquatch",
"last_name":"Bigfoot"}
Maybe this is completely the wrong way of going about this? I'm open to making this work or going a different and more effective route.
Upvotes: 0
Views: 237
Reputation: 907
You could try this to stitch the payload together:
const handleSubmit = (e) => {
var payload = {
httpMethod: "POST",
body: {
TableName: "Users",
Item: {
email: user.email,
first_name: user.first_name,
last_name: user.last_name
}
}
e.preventDefault()
axios.post(url, payload)
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
}
Upvotes: 1
Reputation: 5531
On change , set the event name and value to user.body.Item
not on user
const handleChange = (event) => {
setUser({...user, user.body.Item[event.target.name]: event.target.value})
}
Upvotes: 1