Last active
May 29, 2020 20:18
-
-
Save squamuglia/a474a33889c3b03c6745c01a76993333 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from 'react'; | |
import axios from 'axios'; | |
export default () => { | |
const [image, setImage] = useState(null); | |
const [error, setError] = useState(null); | |
const onSubmit = async (e) => { | |
e.preventDefault(); | |
if (!image) { | |
setError('Missing image'); | |
return; | |
} | |
try { | |
const data = new FormData(); | |
data.append('file', image); | |
await axios.post('YOUR_API_URL/image', data, { | |
headers: { 'content-type': 'multipart/form-data' }, | |
}); | |
} catch (err) { | |
console.error(err); | |
setError(err.response.data); | |
} | |
setError(null); | |
}; | |
return ( | |
<form onSubmit={onSubmit}> | |
<label> | |
Image | |
<input | |
type="file" | |
name="image" | |
onChange={(e) => setImage(e.target.files[0])} | |
/> | |
</label> | |
{error && <p>{error}</p>} | |
<button type="submit">Submit</button> | |
</form> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment