Is anyone decent with React & Apollo, concerni...
# prisma-whats-new
i
Is anyone decent with React & Apollo, concerning auth? My auth requests are sent successfully, however, the tokens don’t get stored. I also tried to manually add a root token but Apollo isn’t reading it for some reason. Any advice?
d
what's your storage logic ?
i
Copy code
loginUser(e) {
    this.props.mutate({
      variables: {
        email: e.target.email.value,
        password: e.target.password.value,
      }
    })
    .then(() => {
      const { email, password } = this.state;
      const response = this.props.mutate({variables: { email, password }});
      localStorage.setItem('token', response.data.authenticateUser.token);
    }).catch((error) => {
      console.log('An error occurred: ', error);
    });
  }
Copy code
const httpLink: ApolloLink = createHttpLink({
  uri: LOCAL_SIMPLE_API
});

let cache: ApolloCache<any> = (new InMemoryCache() as ApolloCache<any>);

const authLink = setContext((_, { headers }) => {
  const token = localStorage.getItem('token');
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : null,
    }
  };
});

const clientOptions = {
  link: authLink.concat(httpLink),
  cache: cache,
};
Note: I’m using TypeScript, and Apollo has a TS bug, so that’s why I’m doing that weird casting crap
k
It seems like you’re not waiting for the async function to return the item from localStorage before initializing it in your headers
Here’s how I’m doing it with AsyncStorage (React Native):
Copy code
const authMiddleware = setContext(operation =>
  AsyncStorage.getItem("token").then(token => {
    return {
      headers: {
        Authorization: `Bearer ${token}` || null
      }
    };
  })
);
i
I’ll try that out real quick
e
in this: const httpLink: ApolloLink = createHttpLink({ uri: LOCAL_SIMPLE_API }); Is LOCAL_SIMPLE_API connected to anything?
i
Yeah
It’s a variable I export from
./constants.ts
e
ok
i
@kaihuang724 - It doesn’t look like you use
operation
k
Yeah just realized - I can take that out.
i
So… I feel stupid now. For manually entering the token, I kept putting
Bearer
in the localStorage value, forgetting that it was already set in my
index.tsx
Let’s see if I can’t figure out the rest now
Okay, so it’s still not getting set
e
i
I’ll try that method out again
Finally got it to work. Thanks guys! @kaihuang724 @ehodges
e
awesome
i
I think the problem I had was that I was going off of the tutorial & changed the names around a bit. (IE: I renamed
graphcool-auth-token
to
token
)
e
ah