@@ -24,7 +24,7 @@ import { entry, on, start } from "yieldmachine";
2424
2525const exampleURL = new URL (" https://example.org/" );
2626function fetchData () {
27- return fetch (exampleURL . toString () );
27+ return fetch (exampleURL);
2828}
2929
3030function Loader () {
@@ -60,6 +60,56 @@ loader.resolved.then(([response]) => {
6060// loader.value; // "success"
6161```
6262
63+ ### Passing parameters to a machine with closures
64+
65+ ``` javascript
66+ import { entry , on , start } from " yieldmachine" ;
67+
68+ // Function taking as many arguments as you like
69+ function GenericLoader (url ) {
70+ function fetchData () {
71+ return fetch (url);
72+ }
73+
74+ function * idle () {
75+ yield on (" FETCH" , loading);
76+ }
77+ function * loading () {
78+ yield entry (fetchData);
79+ yield on (" SUCCESS" , success);
80+ yield on (" FAILURE" , failure);
81+ }
82+ function * success () {}
83+ function * failure () {
84+ yield on (" RETRY" , loading);
85+ }
86+
87+ return idle;
88+ }
89+
90+ // Function taking no arguments that will define our machine
91+ function SpecificLoader () {
92+ const exampleURL = new URL (" https://example.org/" );
93+ return GenericLoader (exampleURL);
94+ }
95+
96+ // Start our specific loader machine
97+ const loader = start (SpecificLoader);
98+ loader .value ; // "idle"
99+
100+ loader .next (" FETCH" );
101+ loader .value ; // "loading"
102+
103+ loader .resolved .then (([response ]) => {
104+ // Use response of fetch()
105+ loader .value ; // "success"
106+ });
107+
108+ /* Or with await: */
109+ // const [response] = await loader.resolved;
110+ // loader.value; // "success"
111+ ```
112+
63113----
64114
65115Further reading / inspiration:
0 commit comments