Reputation: 63
I had an issue where I couldn't specify URI when sending custom headers to my backend server with { ApolloClient }
from 'apollo-boost',
So I had to use { ApolloClient }
from 'apollo-client' instead.
That issue was fixed, but now my mutations aren't being sent to the backend?
My mutation :
import { gql } from 'apollo-boost';
export const LOGIN_USER = gql`
mutation($email: String!, $password: String!) {
loginUser(email: $email, password: $password) {
userId
token
expiresIn
}
}
`
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';
const httpLink = new HttpLink({
uri: 'http://localhost:3001/graphql'
})
const authLink = setContext((_, { headers }) => {
const store = JSON.parse(sessionStorage.getItem('interdevs-data'));
const token = store.token;
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
}
}
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
const login = async (email, password) => {
try {
const user = await loginUser({
variables: {
email,
password
}
});
const { userId, token, expiresIn } = user.data.loginUser;
setUserData({
token: token,
userId: userId,
expiresIn: expiresIn
});
sessionStorage.setItem('interdevs-data', JSON.stringify({
"token": token,
"userId": userId,
"expiresIn": expiresIn
}));
} catch(err) {
console.log('login error: ', err);
setLoginErr(err);
};
};
This is the error I'm getting.
"Error: Network error: Cannot read property 'token' of null"
When I switch it back importing ApolloClient from apollo-boost it works again.
Any help greatly appreciated!
Upvotes: 0
Views: 490
Reputation: 63
found out how to set auth headers with apollo-boost
const client = new ApolloClient({
uri: 'http://localhost:3001/graphql',
request: operation => {
const ssData = JSON.parse(sessionStorage.getItem('data'));
operation.setContext({
headers: {
authorization: ssData ? `Bearer ${ssData.token}` : ''
}
});
}
});
Upvotes: 0
Reputation: 11979
Not 100% sure, but I think the error lies here:
const store = JSON.parse(sessionStorage.getItem('interdevs-data'));
const token = store.token;
If there are no items with the key interdevs-data
, store will be null.
I think you can fix it by doing this:
const store = JSON.parse(sessionStorage.getItem('interdevs-data'));
const token = store ? store.token : null;
Upvotes: 1