Skip to content

Commit ce2bab5

Browse files
add dependency injection snippet
1 parent d3c034b commit ce2bab5

File tree

1 file changed

+34
-2
lines changed

1 file changed

+34
-2
lines changed

docs/README.md

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ In the world full of APIs, we starting to forget the power of plain JavaScript a
88

99
This project tends to use the simplicity of functional React components and the essential mechanism of coroutines to create stateful components with colocation.
1010

11+
## Usage
1112

1213
```javascript
1314
import React from 'react';
@@ -18,15 +19,46 @@ import PostList from 'PostList.react';
1819
async function PostListCo() {
1920
try {
2021
const posts = await Posts.retrieve();
21-
return <PostList posts={posts} />;
22+
return <PostList posts={posts} />
2223
} catch (error) {
23-
return <p>Unable to fetch posts.</p>;
24+
return <p>Unable to fetch posts.</p>
2425
}
2526
}
2627

2728
export default Coroutine.create(PostListCo);
2829
```
2930

31+
### Dependency injection
32+
33+
For the sake of testability you might want to inject instances into your coroutine in the way how React `props` are provided.
34+
35+
You are able to provide `getVariables()` function that receives `props` and `context` and returns an object that will be passed in a coroutine.
36+
37+
```javascript
38+
function getVariables(props) {
39+
return {
40+
postsLoader: new PostsLoader(props.userId)
41+
};
42+
}
43+
44+
async function PostListCo({ postsLoader }) {
45+
try {
46+
const posts = await postsLoader.retrieve();
47+
return <PostList posts={posts} />
48+
} catch (error) {
49+
return <p>Unable to fetch posts.</p>
50+
}
51+
}
52+
53+
export default Coroutine.create(PostListCo, getVariables);
54+
```
55+
56+
In the example above, the result component receives `userId` property and uses it to provide a loader to the coroutine.
57+
58+
```html
59+
<PostListCo userId={...} />
60+
```
61+
3062
## Testing
3163

3264
Please read the [testing guide](./Testing.md).

0 commit comments

Comments
 (0)