Created
February 14, 2020 10:51
-
-
Save alexandrebodin/fedc71c8513bfbb6283cc90ae62755c5 to your computer and use it in GitHub Desktop.
Upload image wiht graphql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import "./App.css"; | |
import { ApolloProvider } from "@apollo/react-hooks"; | |
import gql from "graphql-tag"; | |
import { ApolloClient } from "apollo-client"; | |
import { createUploadLink } from "apollo-upload-client"; | |
import { InMemoryCache } from "apollo-cache-inmemory"; | |
const cache = new InMemoryCache(); | |
const client = new ApolloClient({ | |
cache, | |
link: createUploadLink({ | |
uri: "http://localhost:1337/graphql" | |
}) | |
}); | |
const UPLOAD = gql` | |
mutation($file: Upload!) { | |
upload(file: $file) { | |
name | |
} | |
} | |
`; | |
class App extends React.Component { | |
state = { | |
image: null | |
}; | |
onImageChange = event => { | |
console.log(event.target.files); | |
this.setState({ | |
image: event.target.files[0] | |
}); | |
}; | |
onSubmit = e => { | |
e.preventDefault(); | |
client | |
.mutate({ | |
mutation: UPLOAD, | |
variables: { | |
file: this.state.image | |
} | |
}) | |
.then(res => { | |
console.log(res); | |
}) | |
.catch(err => { | |
console.error(err); | |
}); | |
}; | |
render() { | |
return ( | |
<ApolloProvider client={client}> | |
<form onSubmit={this.onSubmit}> | |
<input | |
type="file" | |
name="files" | |
onChange={this.onImageChange} | |
alt="image" | |
/> | |
<br /> | |
<button type="submit">Send</button> | |
</form> | |
</ApolloProvider> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment