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

explain why you may want to return a function from a resource, instead of just returning a value. #946

Open
NullVoxPopuli opened this issue Jul 13, 2023 · 0 comments
Labels
documentation Improvements or additions to documentation

Comments

@NullVoxPopuli
Copy link
Owner

Example:

const Clock = resource(({ on }) => {
  const now = cell(Date.now());
  const interval = setInterval(() => now.current = Date.now(), 1000);
  on.cleanup(() => clearInterval(interval));

  return now.current;
})

vs

const Clock = resource(({ on }) => {
  const now = cell(Date.now());
  const interval = setInterval(() => now.current = Date.now(), 1000);
  on.cleanup(() => clearInterval(interval));

  return () => now.current;
})

The reason:

  • because the tracked data (.current), would be immediately consumed in the resource() body, the whole thing would be torn down when the clock updates (create a new interval each second). By using a function, only the function invalidates, you retain state, and keep the interval.
@NullVoxPopuli NullVoxPopuli added the documentation Improvements or additions to documentation label Jul 13, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

1 participant