Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved useDynamicMutation API #132

Merged
merged 6 commits into from
Nov 26, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 10 additions & 11 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,25 +121,24 @@ Check out `examples/3-mutation` to see an example of using the `useMutation` hoo

### `useDynamicMutation`

`useDyanmicMutation` is quite similar to `useMutation`, except it is a hook reserved for when you want to **dynamically** pass in variables to the `executeMutation` function _at execution time_. In constrast, `useMutation` applies variables immediately when it is called _at render time_.
`useDynamicMutation` is quite similar to `useMutation`, except it is a hook reserved for when you want to **dynamically** pass in variables to the `executeMutation` function _at execution time_. In constrast, `useMutation` applies variables immediately when it is called _at render time_.

A good example of a case where `useDyanmicMutation` comes in handy is when you need to execute a mutation with variables retrieved from `useQuery` in the same component. With `useMutation`, you'd have to provide a "fallback" `variables` argument, then rely on `useQuery` running to populate the proper `variables` in `useMutation`. With `useDynamicMutation`, this becomes much simpler – see the Example section below.
A good example of a case where `useDynamicMutation` comes in handy is when you need to execute a mutation with variables retrieved from `useQuery` in the same component. With `useMutation`, you'd have to provide a "fallback" `variables` argument, then rely on `useQuery` running to populate the proper `variables` in `useMutation`. With `useDynamicMutation`, this becomes much simpler – see the Example section below.

#### Arguments

| Argument | Type | Description |
| -------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `query` | `string` | The query string for your GraphQL mutation. |
| `parse` | `Js.Json.t => 'response` | A function describing how to parse the JSON returned by your GraphQL API. If using `graphql_ppx_re` or `graphql_ppx` this is provided by accessing the `parse` function on your mutation module. |
| Argument | Type | Description |
| ------------ | --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------|
| `definition` | `(Js.Json.t => 'response, string, UrqlTypes.graphqlDefinition)` | The definition of your Graphql mutation. If using graphql_ppx_re, this is `MyMutation.definition`. |

### Return Type

`useDynamicMutation` returns nearly the same tuple as `useMutation`, containing the result of executing your GraphQL mutation as a record, `result`, and a function for executing the mutation imperatively, `executeMutation`. Unlike `useMutation`, the `executeMutation` function returned by `useDynamicMutation` accepts an argument for `variables` of type `Js.Json.t`.
`useDynamicMutation` returns nearly the same tuple as `useMutation`, containing the result of executing your GraphQL mutation as a record, `result`, and a function for executing the mutation imperatively, `executeMutation`. Unlike `useMutation`, the `executeMutation` function returned by `useDynamicMutation` accepts all your variables as named arguments.

| Return Value | Type | Description |
| ----------------- | -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `result` | `UrqlTypes.hookResponse('response)` | A record containing fields for `fetching`, `data`, `error`, and `response`. `response` is a variant containing constructors for `Data`, `Error`, `Fetching` and `NotFound`. Useful for pattern matching to render conditional UI. |
| `executeMutation` | `{.. variables: Js.Json.t } => Js.Promise.t(Client.Types.operationResult)` | A function for imperatively executing the mutation, which accepts a `variables` argument. |
| Return Value | Type | Description |
| ----------------- | ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `result` | `UrqlTypes.hookResponse('response)` | A record containing fields for `fetching`, `data`, `error`, and `response`. `response` is a variant containing constructors for `Data`, `Error`, `Fetching` and `NotFound`. Useful for pattern matching to render conditional UI. |
| `executeMutation` | `(~myVar1, ~myVar2, ..., ()) => Js.Promise.t(Client.Types.operationResult)` | A function for imperatively executing the mutation, which accepts all the variables as named arguments. |

#### Example

Expand Down
2 changes: 1 addition & 1 deletion examples/3-mutation/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"reason-urql": "link:../../"
},
"devDependencies": {
"@baransu/graphql_ppx_re": "^0.3.2",
"@baransu/graphql_ppx_re": "^0.4.0",
"bs-platform": "6.2.1",
"webpack": "^4.29.6",
"webpack-cli": "^3.2.3",
Expand Down
9 changes: 2 additions & 7 deletions examples/3-mutation/src/Dog.re
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,7 @@ let make =
/* Example of using hooks where the variables are only known when the
mutation runs. */
let (_, executePatMutation) =
Hooks.useDynamicMutation(
~query=Mutations.PatDog.query,
~parse=Mutations.PatDog.parse,
);
Hooks.useDynamicMutation(Mutations.PatDog.definition);

<div className=DogStyles.container>
<img src=imageUrl alt=name className=DogStyles.image />
Expand All @@ -98,9 +95,7 @@ let make =
emoji={j|✋|j}
count={string_of_int(pats)}
hex="db4d3f"
onClick={_ =>
executePatMutation(Mutations.PatDog.make(~key=id, ())) |> ignore
}
onClick={_ => executePatMutation(~key=id, ()) |> ignore}
/>
<EmojiButton
emoji={j|🍖|j}
Expand Down
8 changes: 4 additions & 4 deletions examples/3-mutation/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@
lodash "^4.17.11"
to-fast-properties "^2.0.0"

"@baransu/graphql_ppx_re@^0.3.2":
version "0.3.2"
resolved "https://registry.yarnpkg.com/@baransu/graphql_ppx_re/-/graphql_ppx_re-0.3.2.tgz#6876609be84853b1da6184b7868731066a892851"
integrity sha512-DseaS4enJpd43MyTEQZagbEktCzE0wpI96QSxOYR9AHpkgLNrSaM92yi8FBV8Q4sYmFX9191Bdjp+30Y0KWXwQ==
"@baransu/graphql_ppx_re@^0.4.0":
version "0.4.0"
resolved "https://registry.yarnpkg.com/@baransu/graphql_ppx_re/-/graphql_ppx_re-0.4.0.tgz#24f01e19d030768bba85a8676c70679c8fb63725"
integrity sha512-vCWaBTbLRHDRvl72e80UH1Xo6Rp7JaBJgBgt24jBX1zXPdpvELObwxapmaSdPHK+wI31X0fRJu9z6yD7IAlBDA==

"@emotion/babel-utils@^0.6.4":
version "0.6.10"
Expand Down
9 changes: 9 additions & 0 deletions src/UrqlTypes.re
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,12 @@ type jsResponse('response) = {
[@bs.optional] [@bs.as "error"]
jsError: UrqlCombinedError.combinedErrorJs,
};

type graphqlDefinition('parseResult, 'composeReturnType, 'hookReturnType) = (
// `parse`
Js.Json.t => 'parseResult,
// `query`
string,
// `composeVariables`
(Js.Json.t => 'composeReturnType) => 'hookReturnType,
);
7 changes: 4 additions & 3 deletions src/hooks/UrqlUseMutation.re
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ let useMutation = (~request) => {
(response, executeMutation);
};

let useDynamicMutation = (~query, ~parse) => {
let useDynamicMutation = definition => {
let (parse, query, composeVariables) = definition;
let (responseJs, executeMutationJs) = useMutationJs(query);

let response =
Expand All @@ -72,8 +73,8 @@ let useDynamicMutation = (~query, ~parse) => {
);

let executeMutation =
React.useCallback1(
request => executeMutationJs(Some(request##variables)),
React.useMemo1(
() => composeVariables(request => executeMutationJs(Some(request))),
[|executeMutationJs|],
);

Expand Down
10 changes: 5 additions & 5 deletions src/hooks/UrqlUseMutation.rei
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ let useMutation:
);

let useDynamicMutation:
(~query: string, ~parse: Js.Json.t => 'response) =>
(
UrqlTypes.hookResponse('response),
{.. "variables": Js.Json.t} =>
UrqlTypes.graphqlDefinition(
'parsedResponse,
Js.Promise.t(UrqlClient.ClientTypes.operationResult),
);
'executeMutationFunction,
) =>
(UrqlTypes.hookResponse('parsedResponse), 'executeMutationFunction);