fullstack-tutorial
fullstack-tutorial copied to clipboard
Uncaught (in promise) Error: GraphQL error: Cannot read property 'id' of null
Steps to reproduce:
- Login as a new user (hasn't entered their email yet)
- Select a trip from the home page
- Add trip to cart
- Go to cart
- Click Book All
It will explode with: Uncaught (in promise) Error: GraphQL error: Cannot read property 'id' of null.
Looking at the error more closely reveals that we are caching the guest user somewhere. The error comes back from
// src/datasources/user.js:35
const userId = this.context.user.id;
if (!userId) return;
This means the user context is null
Same error here. Unable to execute the last part of the tutorial - on the server part. This is very disturbing when you want to learn a new piece of knowledge and you find yourself trying to solve a bug in a technology that by definition you don't master yet.
@philohelp seems like refreshing the page is a work around. But is buggy
I am getting the same issue, anyone found a solution?
getting this issue too. Reloading the page seems to solve the issue.
Looks like this is a problem with the authorization header sent by ApolloClient not being updated. On first load of the client, local storage is empty, user authorization token is not set yet. After login, we get the token back from the server and it get set properly in local storage, but headers set in the ApolloClient remain the same.
const client = new ApolloClient({ cache, link: new HttpLink({ uri: 'http://localhost:4000/graphql', headers: { authorization: localStorage.getItem('token'), 'client-name': 'Space Explorer [web]', 'client-version': '1.0.0', }, }), resolvers, typeDefs, });
authorization: localStorage.getItem('token')
Authorization header should be evaluated every time a request is sent or new headers should be set on the ApolloClient after successful login.
How should it be handled ?
Surprisingly this issue is still opened. According to Apollo Client own documentation authentication token should be handled this way: https://stackoverflow.com/questions/58556687/react-apollo-how-to-set-authorization-header-when-user-logs-in
(See first solution by Abderrahim Soubai Elidrissi)
As @gdesjonqueres said the problem is authorization
header didn't update and you can solve as the link he given, if you don't wanna use that way (if you don't want to install apollo-boost
package). Try that way https://www.apollographql.com/docs/react/networking/advanced-http-networking/#customizing-request-logic, it works well to me.
See the fix per https://github.com/apollographql/fullstack-tutorial/pull/103/commits/3558495a59417cde2ff29d96ba7bcb022eb9e684