/
CreateBookmark.jsx
79 lines (75 loc) · 2.03 KB
/
CreateBookmark.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import React from "react";
import { BookmarksContext } from "../context/bookmarks-context";
class CreateBookmark extends React.Component {
static contextType = BookmarksContext;
onInputChange = (event) => {
const key = event.target.id;
if (event.target?.files) {
this.setState({
[key]: event.target.files[0]
})
} else {
this.setState({
[key]: event.target.value,
});
}
};
onFormSubmit = async (event) => {
event.preventDefault();
const data = new FormData()
for (let key in this.state) {
data.append(`bookmark[${key}]`, this.state[key])
}
const response = await fetch(
`${process.env.REACT_APP_BACKEND_URL}/bookmarks`,
{
method: "POST",
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
body: data,
}
);
const { image, bookmark } = await response.json();
this.context.dispatch("add", {...bookmark, image});
this.props.history.push("/bookmarks");
};
render() {
return (
<>
<h1>Create a bookmark</h1>
<form onSubmit={this.onFormSubmit} encType="multipart/form-data">
<label htmlFor="title">Title</label>
<input
type="text"
name="title"
id="title"
onChange={this.onInputChange}
/>
<label htmlFor="url">Url</label>
<input
type="text"
name="url"
id="url"
onChange={this.onInputChange}
/>
<label htmlFor="description">Description</label>
<textarea
name="description"
id="description"
onChange={this.onInputChange}
></textarea>
<label htmlFor="image">Image</label>
<input
type="file"
name="image"
id="image"
onChange={this.onInputChange}
/>
<input type="submit" value="Submit" />
</form>
</>
);
}
}
export default CreateBookmark;