apollo-graphql在react里面的使用

apollo能做到什么

使用

引入

import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import { store, persistor } from './app/store'
import { Provider } from 'react-redux'
import { HelmetProvider } from 'react-helmet-async'
import * as serviceWorker from './serviceWorker'
import './i18n'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloClient  } from 'apollo-client'
import { ApolloLink } from 'apollo-link'
import { createHttpLink } from 'apollo-link-http'
import { onError } from 'apollo-link-error'
import { ApolloProvider } from 'react-apollo'
import { PersistGate } from 'redux-persist/integration/react'
import { Error_MESSAGE } from './app/_types/_globalTypes'
import { ToastContainer, toast } from 'react-toastify'
import 'react-toastify/dist/ReactToastify.css'


const uri = process.env.REACT_APP_API_BASE_URL
const client = new ApolloClient({
    link: ApolloLink.from([
        // error log middleware
        onError(({ graphQLErrors, networkError = {} as any }) => {
            if (graphQLErrors)
                graphQLErrors.map(({ message }: Error_MESSAGE) => toast(message))
            if (networkError) {
        const href = window.location.href
        if (networkError.statusCode === 401 && !href.includes('/login')) {
          window.location.href = '/login'
        }
        const text = networkError?.bodyText ?? ''
        if (text) {
          toast.error(networkError?.bodyText??'')
        }
      }
        }),
        createHttpLink({
            uri,
            credentials: 'include',
        }),
    ]),
    cache: new InMemoryCache(),
});

ReactDOM.render(
  <React.StrictMode>
    <ApolloProvider client={client}>
      <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
          <HelmetProvider>
            <App/>
            <ToastContainer />
          </HelmetProvider>
        </PersistGate>
      </Provider>
    </ApolloProvider>
  </React.StrictMode>,

  document.getElementById('root')
)

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister()

ajax 交互

export const GET_LOGIN = gql`
  query Login( $password: String, $account: String ) {
    login(password: $password, account: $account) {
      account
      avatarUrl
      nickname
      updateTime
    }
  }
`
// typescript 需要定义返回内容字段类型
export interface LOGIN_MANAGER {
  /**
   * 账号
   */
  account: string | null;

  /**
   * 用户头像
   */
  avatarUrl: string | null;

  /**
   * id
   */
  id: string | null;

  /**
   * 昵称
   */
  nickname: string | null;

  /**
   * 更新时间
   */
  updateTime: number | null;
}

页面使用

import { useLazyQuery } from '@apollo/react-hooks'
import { LOGIN_DATA, GET_LOGIN } from './gqls'
……
const [getLogin, { loading: loginLoading, data: loginInfo }] = useLazyQuery(GET_LOGIN)

// 提交事件出发
const submitLogin = () => {
    // 验证
    if (!validateFormSync(formData)) return false
    getLogin({
      variables: formData
    })
  }

apollo-link-state

可以使用apollo-link-state 存储数据

With apollo-link-state, you no longer have to maintain a second store for local state. You can instead use the Apollo Client cache as your single source of truth that holds all of your local data alongside your remote data. To access or update your local state, you use GraphQL queries and mutations just like you would for data from a server.

apollo-link-state 使用

import { withClientState } from 'apollo-link-state';

// This is the same cache you pass into new ApolloClient
const cache = new InMemoryCache(...);

const stateLink = withClientState({
  cache,
  resolvers: {
    Mutation: {
      updateNetworkStatus: (_, { isConnected }, { cache }) => {
        const data = {
          networkStatus: {
            __typename: 'NetworkStatus',
            isConnected
          },
        };
        cache.writeData({ data });
        return null;
      },
    },
  }
});

demo参考

demo

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。