美文网首页
Taro hooks - apollo client 整合

Taro hooks - apollo client 整合

作者: 吴占超 | 来源:发表于2022-10-31 11:04 被阅读0次

感谢京东Taro项目组。
https://taro.jd.com/
感谢Apollo。
https://www.apollographql.com/docs/react
感谢开源社区的各位大大分享。

背景:
希望使用graphql方案进行taro 小程序开发。
选型过程:
1、apollo 2、urql
排除 urql 打包编译错误,包过大,使用apollo

修正app.ts 为 app.tsx

import { ApolloProvider } from '@apollo/client';
import React, { FC } from 'react';
import './app.scss';
import { client } from './utils/apollo-helper';

// class App extends Component {
//   componentDidMount() {}

//   componentDidShow() {}

//   componentDidHide() {}

//   componentDidCatchError() {}

//   // this.props.children 是将要会渲染的页面
//   render() {
//     return this.props.children;
//   }
// }
const App: FC = (prop) => {
  return <ApolloProvider client={client}>{prop.children}</ApolloProvider>;
};

export default App;

创建 client [src/urils/apollo-helper.ts]

import {
  ApolloClient,
  ApolloLink,
  createHttpLink,
  InMemoryCache,
} from '@apollo/client';
import Taro from '@tarojs/taro';

const graphQLServerUrl = 'http://127.0.0.1:8088/graphql';

const httpLink = createHttpLink({
  uri: graphQLServerUrl,
  async fetch(url, options) {
    console.log('url = ', url, options);
    const res = await Taro.request({
      url: url.toString(),
      method: (options?.method || 'POST') as 'POST' | 'GET',
      header: {
        'content-type': 'application/json',
      },
      data: options?.body,
      success: console.log,
    });

    return { text: async () => JSON.stringify(res.data) } as any;
  },
});

export const client = new ApolloClient({
  link: ApolloLink.from([httpLink]),
  cache: new InMemoryCache(),
});

替换 fetch 实现从web到taro fetch的 核心替换

demo

import { useQuery } from '@apollo/client';
import { View } from '@tarojs/components';
import { FC } from 'react';
import { projectQuery } from '../../service/demo';
// import { useRequest } from 'taro-hooks';

const projectQuery = gql`
  query findAll($param: FindAllInput!) {
    projectAll(param: $param) {
      name
      systemName
    }
  }
`;

const Index: FC = () => {
  const { loading, error, data } = useQuery(projectQuery, {
    variables: {
      param: {
        where: {
          name: {
            _like: '%测试%',
          },
        },
        limit: 2,
      },
    },
  });
  return <View>{data?.projectAll?.map((p) => p.name)}</View>;
};

export default Index;
image.png

相关文章

网友评论

      本文标题:Taro hooks - apollo client 整合

      本文链接:https://www.haomeiwen.com/subject/kwyrtdtx.html