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

Negative numbers in useData for counting from top #69

Closed
wants to merge 1 commit into from
Closed
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ return <div classList={{ "grey-out": isRouting() }}>

### useData

Retrieves the return value from the data function. You can access parent data by passing a number to indicate ancestor. No argument is the route's own data, `1` is the immediate parent, `2` is the parent's parent, and so on.
Retrieves the return value from the data function. You can access parent data by passing a number to indicate ancestor. No argument (or `0`) is the route's own data, `1` is the immediate parent, `2` is the parent's parent, and so on. Alternatively, `-1` is the top-level route's data, `-2` is the immediate child, etc.

```js
const user = useData();
Expand Down
19 changes: 17 additions & 2 deletions src/routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,23 @@ export const useSearchParams = <T extends Params>(): [

export const useData = <T>(delta: number = 0) => {
let current = useRoute();
let n = delta;
while (n-- > 0) {
let n: number;
if (delta >= 0) {
// Nonnegative numbers count number of levels up from route
n = delta;
} else if (delta < 0) {
// Negative numbers count backwards, down from root route
let count = 1, ancestor = current;
while (ancestor.parent) {
ancestor = ancestor.parent;
count++;
}
n = count + delta;
if (n < 0) {
throw new RangeError(`Route descendant ${delta} is out of bounds`);
}
}
while (n!-- > 0) {
if (!current.parent) {
throw new RangeError(`Route ancestor ${delta} is out of bounds`);
}
Expand Down