0
votes

I'm new to using GraphQL. Very much accustomed to using Redux, but given new requirements I have begun using GraphQL on the backend and also apollo client for local state management. I am trying to implement a "isLoggedIn" boolean to determine wherever the user is logged in or not.

From what I've read, this is how you do it:

import withApollo from 'next-with-apollo';
import ApolloClient, { InMemoryCache, gql } from 'apollo-boost';
import {typeDefs, resolvers} from '../resolvers/index';

const cache = new InMemoryCache();
cache.writeData({
  data: {
    User: {
      isLoggedIn: false,
      email: "empty"
    }
  }
})

    const IS_LOGGED_IN = gql`
query IsLoggedIn{
  User{
    isLoggedIn
  }
}`

`

export default withApollo(
  ({ ctx, headers, initialState }) =>
    new ApolloClient({
      uri: "http://localhost:4000/auth/authorize",
      cache: cache,
      headers: {
        authorization: ''},
      typeDefs,
      resolvers: {
        User : {
          isLoggedIn: (_, _args, {cache}) => {
            const {isLoggedIn} = cache.readQuery({query: IS_LOGGED_IN});
            return isLoggedIn;
          }
        }
      }

    }));

I create a cache object before state initialization so I can write in the values I want initially (loggedin = false).

Then I wrote a query IS_LOGGED_IN to query the state.

Afterwards I initialize the Apollo client state and also add a resolver for the query.

I have a feeling I am making a critical error but unsure what it is. The error I am currently looking at says:

Missing field __typename in {
  "isLoggedIn": false,
  "email": "empty"
}
1

1 Answers

0
votes

My set up was wrong. Followed this guys setup and everything is working fine: https://www.youtube.com/watch?v=CnhHeSAAbRM