【问题标题】:How to transform received data from @apollo/react-hooks如何转换从@apollo/react-hooks 接收到的数据
【发布时间】:2020-06-19 23:42:53
【问题描述】:

我正在使用``查询:

const GET_COMMENTS = gql`
    query getComments {
        getComments (where: {code: "/about-us" }) {
            id
            text
            createdAt
        }
    }
`
....
const { loading, error, data } = useQuery(GET_COMMENTS);

在我的代码中...

代码是从服务器中获取 cmets 的注释对象是 date: string! 属性,我想将这个 date: string! 转换为 javascript 日期 (new Date(comment.date)) 如何在获取数据后直接执行此操作?

我不想转换每次调用的渲染。

有这样的吗?:

const { loading, error, data } = 
   useQuery(
      GET_COMMENTS, 
      {
         transform: (data) => data.map(comment => ({...comment , date: new Date(comment.date)}) )
      }
   );

感谢您的帮助!

【问题讨论】:

    标签: graphql react-hooks react-apollo


    【解决方案1】:

    缓存类型策略中的merge function 就是您要查找的内容。它允许您定义将传入数据写入缓存的自定义策略。

    创建缓存时,您可以定义如何写入特定字段。假设date 字段属于Comment 类型:

    const cache = new InMemoryCache({
      typePolicies: {
        Comment: {
          fields: {
            date: {
              merge(_, date) {
                return new Date(date);
              },
            },
          },
        },
      },
    });
    

    【讨论】:

      【解决方案2】:

      试试这个:

      const { loading, error, data } = useQuery(GET_COMMENTS, {
        onCompleted: data => {
          // Do changes here
        }
      });
      

      你可以在这里查看https://www.apollographql.com/docs/react/api/react/hooks/

      【讨论】:

        猜你喜欢
        • 2020-01-25
        • 2021-05-01
        • 2020-01-11
        • 2019-09-14
        • 2020-10-22
        • 2020-06-13
        • 2023-04-07
        • 2020-09-18
        • 2019-05-31
        相关资源
        最近更新 更多