graphql - 如何转换从@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)}) )
}
);
谢谢您的帮助!
解决方案
您正在寻找缓存类型策略中的合并功能。它允许您定义将传入数据写入缓存的自定义策略。
创建缓存时,您可以定义如何写入特定字段。假设该date
字段属于以下Comment
类型:
const cache = new InMemoryCache({
typePolicies: {
Comment: {
fields: {
date: {
merge(_, date) {
return new Date(date);
},
},
},
},
},
});
推荐阅读
- python - 如果使用 python 制作 android 应用程序,像 pyaudio 这样的 python 模块是否可以在 android 中工作?
- python - 在没有父对象名称的MongoDB中获取字段值
- ruby - 无法通过 rvm 更改 gemset
- javascript - 提交按钮时显示警报
- android - Android Native JNI Parcel 读取数据
- swift - Firebase 身份验证匿名帐户创建然后调用带有 context.auth.uid 错误的函数
- angular - 角度 8 中的组件加载
- r - 在 tibble 中取消嵌套多个 tibble 以拆分 Mutli-Select 调查问题
- python - 在 Python 中访问 shell 变量
- azure-devops - 如何在 Azure Devops 中不使用故事点