从Apollo商店获取价值

我想访问保存在Apollo商店中的值。

//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")
);

现在,在我的个人资料组件中,我要访问缓存的isAuthenticated值。

import React from "react";

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

我需要添加什么?

谢谢。

xj0605 回答:从Apollo商店获取价值

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';
}

本文链接:https://www.f2er.com/2517108.html

大家都在问