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

[hooks] Allow changing cursor path dynamically #135

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
4 changes: 3 additions & 1 deletion docs/hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ const List = function(props) {
// Using a function so that your cursors' path can use the component's props etc.
const {colors} = useBranch({
colors: [props.alternative ? 'alternativeColors' : 'colors']
});
}, [props.alternative]);

function renderItem(color) {
return <li key={color}>{color}</li>;
Expand All @@ -240,6 +240,8 @@ const List = function(props) {
export default List;
```

Note that you need to pass an array of dependencies as a second argument. If dependencies are not specified, the path will not be re-computed.

### Clever vs. dumb components

Now you know everything to use a Baobab tree efficiently with React.
Expand Down
15 changes: 10 additions & 5 deletions src/hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export function useRoot(tree) {
return state;
}

export function useBranch(cursors) {
export function useBranch(cursors, deps) {
if (!isPlainObject(cursors) && typeof cursors !== 'function')
invalidMapping(name, cursors);

Expand All @@ -63,14 +63,19 @@ export function useBranch(cursors) {
const mapping = typeof cursors === 'function' ? cursors(context) : cursors;
const watcher = context.tree.watch(mapping);

watcher.on('update', () => {
const updateValue = () => {
const obj = watcher.get();
obj.dispatch = (fn, ...args) => fn(context.tree, ...args);
setState(obj);
});
};

// cursors have changed - update value immediately
updateValue();

watcher.on('update', updateValue);

return () => watcher.release();
}, [cursors]);
}, deps || []);

return state;
}
}
2 changes: 1 addition & 1 deletion test/hook.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ describe('Hook', function() {
name: ['name'],
surname: props.path
};
});
}, [props.path]);
return (
<span>
Hello {data.name} {data.surname}
Expand Down