Skip to content

Instantly share code, notes, and snippets.

@alexandrebodin
Created February 14, 2020 10:51
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alexandrebodin/fedc71c8513bfbb6283cc90ae62755c5 to your computer and use it in GitHub Desktop.
Save alexandrebodin/fedc71c8513bfbb6283cc90ae62755c5 to your computer and use it in GitHub Desktop.
Upload image wiht graphql
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