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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
|
import React, { Component } from 'react';
import { Mutation } from 'react-apollo';
import Router from 'next/router';
import { CREATE_ITEM_MUTATION } from '../queries/queries.graphql';
import Error from './ErrorMessage';
import Form from './styles/Form';
import formatMoney from '../lib/formatMoney';
class CreateItem extends Component {
state = {
title: '',
description: '',
image: '',
largeImage: '',
price: 0,
};
handleChange = e => {
const { name, value, type } = e.target;
const val = type === 'number' ? parseFloat(value) : value;
this.setState({ [name]: val });
};
uploadFile = async e => {
this.setState({ loading: true });
const files = e.currentTarget.files;
const data = new FormData();
data.append('file', files[0]);
data.append('upload_preset', 'sickfits');
// use the file endpoint
const res = await fetch('https://api.cloudinary.com/v1_1/wesbos/image/upload', {
method: 'POST',
body: data,
});
const file = await res.json();
this.setState({
image: file.secure_url,
largeImage: file.eager[0].secure_url,
loading: false,
});
};
render() {
return (
<Mutation mutation={CREATE_ITEM_MUTATION} variables={this.state}>
{(createItem, { loading, error }) => (
<Form
data-test
onSubmit={async e => {
e.preventDefault();
const { data: { createItem: item } } = await createItem();
Router.push({
pathname: `/item`,
query: { id: item.id },
});
}}
>
<h2>Sell an Item.</h2>
<Error error={error} />
<fieldset disabled={loading} aria-busy={loading}>
<label htmlFor="file">
Image
<input
required
id="file"
onChange={this.uploadFile}
type="file"
accept=".png, .jpg, .jpeg"
/>
{this.state.image ? (
<img src={this.state.image} width="100" alt={this.state.title} />
) : null}
</label>
<label htmlFor="title">
Title
<input
required
value={this.state.title}
onChange={this.handleChange}
type="text"
name="title"
id="title"
placeholder="Title"
/>
</label>
<label htmlFor="price">
Price {this.state.price && formatMoney(this.state.price)}
<input
required
type="number"
id="price"
name="price"
min="0"
value={this.state.price}
onChange={this.handleChange}
/>
</label>
<textarea
id="description"
required
name="description"
value={this.state.description}
onChange={this.handleChange}
placeholder="The desc for this item"
/>
<button disabled={this.state.loading} type="submit">
Submit
</button>
</fieldset>
</Form>
)}
</Mutation>
);
}
}
export default CreateItem;
|