reactjsapolloreact-apolloapollo-clientapollo-cache-inmemory

Get value from Apollo Store


I want to access a value saved in Apollo Store.

//apollo.js
import ApolloClient from 'apollo-boost';
import gql from 'graphql-tag';

export const client = new ApolloClient({
  uri: 'https://localhost:8000/graphql/',
  clientState: {
    defaults: {
      cartItems: [],
      isAuthenticated: localStorage.getItem('token'),
    },
    resolvers: {
      Mutation: {
        updateCart: async (_, { cartItems }, { cache, getCacheKey }) => {
          await cache.writeData({ data: { cartItems } });
          return null;
        },
      },
    },
    typeDefs: gql`
      type CartItem {    
        id: Int    
        price: Float
        cant: Int
      }  
      type Mutation {    
        updateCart(cartItems: [CartItem]!)  
      }  
      type Query {    
        isAuthenticated: Boolean    
        cartItems: [CartItem]  
      }
    `,
  },
});
//index.js
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Route, Switch } from "react-router-dom";

import Profile from "./views/Profile";

import { ApolloProvider } from '@apollo/react-hooks';

import { client } from './apollo';

ReactDOM.render(
  <>
    <BrowserRouter>
      <ApolloProvider client={client}>
        <Switch>
          <Route path="/profile" component={Profile} />
        </Switch>
      </ApolloProvider>
    </BrowserRouter>
  </>,
  document.getElementById("root")
);

Now in my Profile component I want to access the isAuthenticated value that is cache.

import React from "react";

export default function Profile() {
  if(/* Get isAuthenticated value from store*/)
    return 'You are in';
  else
    return 'You must loggin';
}

What do I need to add?

Thanks in advance.


Solution

  • import { useQuery } from "@apollo/react-hooks";
    import gql from "graphql-tag";
    
    const IS_AUTHENTICATED = gql`
      {
        isAuthenticated cartItems @client
      }
    `;
    
    export default function Profile() {
      const { data, client } = useQuery(IS_AUTHENTICATED);
      if(data && data.isAuthenticated)
        return 'You are in';
      else
        return 'You must loggin';
    }