Skip to main content

Updating Data

Nau can automatically add objects to a list (connection) on cache based on mutation results. Using directives such as @appendNode will automatically add a element to a connection on the cache based on mutation results.

Let's look at an example mutation.

mutation AddItemMutation($input: AddItemInput!) {
addItem(input: $input) {
item {
name
}
}
}

Attach @prependNode to the item field. Using @prependNode you can add the element to the top of the list.

mutation AddItemMutation($input: AddItemInput!, $connections: [String!]!) {
addItem(input: $input) @prependNode(connections: $connections) {
item {
name
}
}
}

Run graphql-codegen.

yarn graphql-codegen

Let's try to use this mutation.

src/List.tsx
import {
AddItemMutationDocument,
List_PaginationQueryDocument,
List_UserFragment,
} from './generated/graphql';

gql` /* GraphQL */
fragment List_user on User
@argumentDefinitions(count: { type: "Int", defaultValue: 2 }, cursor: { type: "String" })
@refetchable(queryName: "List_PaginationQuery") {
id
items(first: $count, after: $cursor) @pagination {
edges {
node {
name
}
}
}
}

mutation AddItemMutation($input: AddItemInput!, $connections: [String!]!) {
addItem(input: $input) {
item @prependNode(connections: $connections) {
name
}
}
}
`;

const List: React.FC<{ user: List_UserFragment }> = ({ user }) => {
// ...

const [addItem] = useMutation(AddItemMutationDocument);

return (
<>
{/* ... */}
<Button
onClick={() =>
void addItem({
variables: {
input: { itemName: 'new item', userId: user.id },
connections: [user.items._connectionId],
},
})
}
>
Add Item
</Button>
{/* ... */}
</>
);
};

Now you can add the element to the top of the list based on the mutation result.

Using @appendNode, you can do the opposite, adding the element to the bottom of the list. Other directives such as @deleteRecord delete data based on mutation results.