summaryrefslogtreecommitdiffstats
path: root/components/UpdateItem.js
blob: 8ca8b7376681681cfbe700f56c249fb1ad61626b (plain)
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
import React, { Component } from 'react'
import { graphql, gql, compose } from 'react-apollo'
import { SINGLE_LINK_QUERY, UPDATE_LINK_MUTATION } from '../queries';

class UpdateLink extends Component {

  state = {
    ...this.props.findItem.Item,
    price: 0,
    fullPrice: 0
  }

  saveToState = (e) => {
    let { name, value, type } = e.target;
    if (type === 'number') {
      value = parseInt(value);
    }

    this.setState({ [name]: value });
  }

  render() {
    return (
      <div>

        <h2>Edit {this.props.id}</h2>
        { this.state.loading ? 'LOADING...' : 'Ready!' }
        <form onSubmit={this._createLink}>

          <label htmlFor="title">Title</label>
          <input value={this.state.title} name="title" onChange={this.saveToState} type='text'/>

          <label htmlFor="description">Description</label>
          <textarea value={this.state.description} name="description" onChange={this.saveToState}></textarea>

          <label htmlFor="price">Price</label>
          <input type="number" name="price" onChange={this.saveToState} value={this.state.price} />

          <label htmlFor="fullPrice">Full Price</label>
          <input type="number" name="fullPrice" onChange={this.saveToState} value={this.state.fullPrice} />

          <button type="submit">Save...</button>
        </form>
      </div>
    )
  }

  _createLink = async (e) => {
    e.preventDefault();
    // pull the values from state
    const { description, title } = this.state
    const { id } = this.props;
    // create a mutation
    // TODO: handle any errors
    // turn loading on
    this.setState({ loading: true });
    console.log(this.state);
    const res = await this.props.updateItem({
      // pass in those variables from state
      variables: {
        ...this.state
      }
    });
    this.setState({ loading: false });
  }

}

const ComponentWithMutations = compose(
  // First, query for getting the link
  graphql(SINGLE_LINK_QUERY, {
    name: 'findItem',
    options: ({ id }) => ({
      variables: { id }
    })
  }),
  // Second, the mutation for updating the link
  graphql(UPDATE_LINK_MUTATION, { name: 'updateItem' })
)(UpdateLink);


export default ComponentWithMutations;