首页 > 解决方案 > 如何转换从@apollo/react-hooks 接收到的数据

问题描述

我正在使用``查询:

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

在我的代码中...

代码在评论对象中从服务器获取评论是一个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)}) )
      }
   );

谢谢您的帮助!

标签: graphqlreact-hooksreact-apollo

解决方案


您正在寻找缓存类型策略中的合并功能。它允许您定义将传入数据写入缓存的自定义策略。

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

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

推荐阅读