After uploading a file to the server returning an empty object. I have tried all the solution on the internet. but still didn't find what's wrong in my code.
solution tried
client setup
const httpLink = createUploadLink({
uri: 'http://localhost:5000/graphql',
})
const authLink = setContext((_, { headers }) => {
const token = localStorage.getItem('token')
return {
headers: {
...headers,
authorization: token
}
}
})
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
onError: ({ networkError, graphQLErrors }) => {
console.log("graphQLErrors", graphQLErrors);
console.log("networkError", networkError);
},
})
client mutation
const [createAd, { loading }] = useMutation(gql`
mutation createAd($file: Upload!) {
createAd(file: $file) {
message
}
}
`, {
onCompleted(data) {
console.log(data)
}, onError(data) {
console.log(data)
}
})
const handleUploadFile = ({
target: {
validity,
files: [file]
}
}) => {
if (validity.valid) {
console.log(file)
createAd({ variables: { file } }).then(() => {
apolloClient.resetStore()
})
}}
<input type="file" required onChange={handleUploadFile} />
Server graphql schema
type Mutation {
createAd(file: Upload!): Return!
}
type Return {
data: String,
message: String,
error: String
}
Server mutation
async createAd(_, {file}, { request }) {
try {
console.log('-- runs --')
console.log(file) // returning empty object
const photo = await file
console.log(photo) // still returning empty object, whats wrong?
return {
message: 'uploadeding',
data: `tesst ${JSON.stringify(photo)}`
}
} catch (err) {
console.log(err)
}
}
I was importing Apollo client from apollo-boost to setup the createUploadLink I need to import apollo client from apollo-client not apollo-boost, as said in this issue https://github.com/jaydenseric/apollo-upload-client/issues/114
I change my setup to
import ApolloClient from "apollo-client"; // here where I did the mistake
import { ApolloProvider } from "@apollo/react-hooks";
import { InMemoryCache } from "apollo-cache-inmemory";
import { setContext } from "apollo-link-context";
import { createUploadLink } from "apollo-upload-client";
const link = createUploadLink({
uri: "http://localhost:5000/graphql"
});
const authLink = setContext((_, { headers }) => {
const token = localStorage.getItem("token");
return {
headers: {
...headers,
authorization: token
}
};
});
const client = new ApolloClient({
link: authLink.concat(link),
cache: new InMemoryCache(),
onError: ({ networkError, graphQLErrors }) => {
console.log("graphQLErrors", graphQLErrors);
console.log("networkError", networkError);
}
});