From b1600adec47a04f60e1da07d94a3ed3906ff5aee Mon Sep 17 00:00:00 2001 From: Wes Bos Date: Thu, 14 Jun 2018 16:44:21 -0400 Subject: starter files --- .../frontend/components/CreateItem.js | 148 +++++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 finished-application/frontend/components/CreateItem.js (limited to 'finished-application/frontend/components/CreateItem.js') diff --git a/finished-application/frontend/components/CreateItem.js b/finished-application/frontend/components/CreateItem.js new file mode 100644 index 0000000..503b3cb --- /dev/null +++ b/finished-application/frontend/components/CreateItem.js @@ -0,0 +1,148 @@ +import React, { Component } from 'react'; +import { Mutation } from 'react-apollo'; +import Router from 'next/router'; +import wait from 'waait'; +import gql from 'graphql-tag'; +import Error from './ErrorMessage'; +import Form from './styles/Form'; +import formatMoney from '../lib/formatMoney'; +import { ALL_ITEMS_QUERY } from './Items'; +import { PAGINATION_QUERY } from './Pagination'; + +const CREATE_ITEM_MUTATION = gql` + mutation CREATE_ITEM_MUTATION( + $description: String! + $title: String! + $price: Int! + $image: String + $largeImage: String + ) { + createItem( + description: $description + title: $title + price: $price + image: $image + largeImage: $largeImage + ) { + id + } + } +`; + +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 ( + + {(createItem, { loading, error }) => ( +
{ + e.preventDefault(); + const { data: { createItem: item } } = await createItem(); + // we wait 0 ms so it puts the router push at the end of the call stack. This ensures that refetchQueries runs before we unmount the component :) + await wait(); + Router.push({ + pathname: `/item`, + query: { id: item.id }, + }); + }} + > +

Sell an Item.

+ +
+ + + +