Skip to content

Instantly share code, notes, and snippets.

@squamuglia
Last active May 29, 2020 20:18
Show Gist options
  • Save squamuglia/a474a33889c3b03c6745c01a76993333 to your computer and use it in GitHub Desktop.
Save squamuglia/a474a33889c3b03c6745c01a76993333 to your computer and use it in GitHub Desktop.
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