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

Add memoization to resources #3

Closed
Olian04 opened this issue Nov 5, 2022 · 1 comment
Closed

Add memoization to resources #3

Olian04 opened this issue Nov 5, 2022 · 1 comment
Assignees
Labels
enhancement New feature or request

Comments

@Olian04
Copy link
Owner

Olian04 commented Nov 5, 2022

const A = createAtom({
  default: 42,
})

const C = createResource({
  get: async () => {
    return await fetch(`/${A.get()}`);
  }
);

await C.get(); // network request
await C.get(); // cached

A.set(3);
await C.get(); // network request
await C.get(); // cached

A.set(42);
await C.get(); // cached

A.invalidate();
await C.get(); // network request
await C.get(); // cached

Memoization will stringify and hash all dependencies, it will then store the return value of the resource/selector to be reused at a later time if the same dependency hash is encountered again.

Resources are memoized selectors optimized for cacheable, IO bound, or computationally heavy operations. Such as network requests, reading from a file, or calculating a complex calculation.

Ex:

const fileName = createAtom({
  default: 'cat.png',
})

const file = createResource({
  get: async ({ get }) => {
    return fetch(`/${fileName.get()}`)
  }
})

const fileEdges = createResource({
  get: async ({ get }) => {
    return getEdges(await file.get()) 
  }
})

createEffect(async () => {
  console.log(await fileEdges.get())
})
@Olian04 Olian04 added the enhancement New feature or request label Nov 5, 2022
@Olian04 Olian04 self-assigned this Nov 5, 2022
@Olian04 Olian04 changed the title Add memorization Add memoization Nov 13, 2022
@Olian04 Olian04 changed the title Add memoization Add memoization to resources Nov 13, 2022
@Olian04
Copy link
Owner Author

Olian04 commented Feb 15, 2023

Closed in favor of #28

@Olian04 Olian04 closed this as completed Feb 15, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant