我有一个用作react-table数据网格的函数。它最初是通过本地状态从父组件中的 Apollo 填充的,网格中的每一行都是数组中的对象。
当网格中的单元格发生变化时,整条线对象都会被写入状态。
我正在尝试使用 useEffect 触发一个突变,将这些状态更改写回数据库,但我正在努力解决两个主要问题:
主要功能(部分)
function Table2({ columns, data }) {
const [lines, setLines] = useState(data);
const [updateLine, {loading, error }] = useMutation(UPDATE_ITEM_MUTATION, {
variables:{ ...lines}
});
useEffect(() => {
updateLine
},[lines]);
const updateMyData = (rowIndex, columnID, value) => {
setLines(getLines =>
getLines.map((row, index) => {
if (index === rowIndex) {
console.log(row)
return {
...lines[rowIndex],
[columnID]: value
};
}
return row;
})
);
};
Run Code Online (Sandbox Code Playgroud)
还有突变……
const UPDATE_ITEM_MUTATION = gql`
mutation UPDATE_LINE_MUTATION( …Run Code Online (Sandbox Code Playgroud) 假设我有以下 GraphQL 类型:
type User {
id: String!
posts: [Post!]!
}
type Post {
id: String!
text: String,
}
Run Code Online (Sandbox Code Playgroud)
这是返回更新后的帖子的突变:
mutation addNewPost(
$userId: String!
$text: String!
) {
addNewPost(userId: $userId, text: $text) {
id
text
}
}
Run Code Online (Sandbox Code Playgroud)
运行此突变后,我的缓存包含帖子的新条目。如何将其添加到用户的帖子数组中?我尝试过cache.writeQuery和cache.modify但我无法弄清楚。
我想通过 GrahQL 和 React 保存一个大表单。我将所有表单值都放在一个变量名中:formValue 有没有办法将“formValue”传递给这样的查询?
const [toSaveUserProfile] = useMutation(SAVE_USER_PROFILE)
toSaveUserProfile({ variables: formValue })
const SAVE_USER_PROFILE = gql`
mutation saveUserProfile($profileId: String!) {
updateProfile(profile: { formValue }) {
id
}
}
`
Run Code Online (Sandbox Code Playgroud)
或者我应该一一传递所有字段并像这样定义它们的类型?
const [toSaveUserProfile] = useMutation(SAVE_USER_PROFILE)
toSaveUserProfile({ variables: formValue })
const SAVE_USER_PROFILE = gql`
mutation saveUserProfile($id: String!, $firstName: String, $lastName: String, $age: Int, ......) {
updateProfile(profile: { id: $id, firstName: $firstName, lastName: $lastName, age:$age, ......}) {
id
}
}
`
Run Code Online (Sandbox Code Playgroud)
模式看起来像这样
updateProfile(profile: ProfileDTOInput!): ProfileDTO
type ProfileDTO {
address: String …Run Code Online (Sandbox Code Playgroud) 我仍然无法理解 Hooks。我经常遇到它抱怨我正在做的问题Invalid hook call。
这次,是尝试useMutation在自定义挂钩中使用 Apollo 的挂钩时。
如果有人能告诉我我做错了什么,我将不胜感激。
组件(我在其中调用自定义挂钩)
export default function MyComponent() {
const { loading, error, data } = useQuery( GET_ORDERS );
const setOrdersInMetafields = ( orders: Array<OrderModel> ) => {
metafieldResp = useSetMetafields( { customerId, value: orders, field: 'duplicateOrders' } );
}
@useEffect( () => {
setOrdersInMetafields( orders );
}, [ orders ] );
}
Run Code Online (Sandbox Code Playgroud)
定制挂钩
export const useSetMetafields( { customerId, value, field }, { customerId: string, value: any, field: string } ) …Run Code Online (Sandbox Code Playgroud) reactjs next.js apollo-client react-hooks react-custom-hooks