r/reactjs • • Sep 01 '19

Beginner's Thread / Easy Questions (September 2019)

Previous two threads - August 2019 and July 2019.

Got questions about React or anything else in its ecosystem? Stuck making progress on your app? Ask away! We’re a friendly bunch.

No question is too simple. πŸ€”


πŸ†˜ Want Help with your Code? πŸ†˜

  • Improve your chances by putting a minimal example to either JSFiddle or Code Sandbox. Describe what you want it to do, and things you've tried. Don't just post big blocks of code!
  • Pay it forward! Answer questions even if there is already an answer - multiple perspectives can be very helpful to beginners. Also there's no quicker way to learn than being wrong on the Internet.

Have a question regarding code / repository organization?

It's most likely answered within this tweet.


New to React?

Check out the sub's sidebar!

πŸ†“ Here are great, free resources! πŸ†“


Any ideas/suggestions to improve this thread - feel free to comment here!


Finally, an ongoing thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!

37 Upvotes

384 comments sorted by

View all comments

Show parent comment

3

u/argiebrah Sep 20 '19

Solved! I moved the axios post inside the onsubmit handler.

import React, { useState } from 'react'
import axios from 'axios'

const AddUserForm = props => {
	const initialFormState = { id: null, name: '', email: '' }
	const [ user, setData ] = useState(initialFormState)

	const handleInputChange = event => {
		const { name, value } = event.target

	
		setData({ ...user, [name]: value })
	}



	return (
		<form
			onSubmit={event => {
				event.preventDefault()
				if (!user.name || !user.email) return
				axios
				.post('http://localhost:3000/users', user)
				.then(() => console.log('User Created'))
				.catch(err => {
				  console.error(err);
				})
				props.addUser(user)
				setData(initialFormState)
			}}
		>
			<label>Name</label>
			<input type="text" name="name" value={user.name} onChange={handleInputChange} />
			<label>email</label>
			<input type="text" name="email" value={user.email} onChange={handleInputChange} />
			<button>Add new user</button>
		</form>
	)
}