fabian-hiller / valibot

The modular and type safe schema library for validating structural data 🤖
https://valibot.dev
MIT License
6.32k stars 204 forks source link

Feature: `memoize` result of asynchronous schema #923

Open GregOnNet opened 1 week ago

GregOnNet commented 1 week ago

Preface - valibot is awesome

Thank you all for developing this library. It is the most type-safe library, I have ever used. It comes with great DX & the docs become better and better.

Use Case

Forms:

New action memoize

Wouldn't it be nice if we could memoize the executions inside a schema, where it is needed? We could provide a synchronous and an asynchronous version...

memoize
memoizeAsync

Example

v.pipeAsync(
  v.string(),
  v.memoizeAsync(
    v.customAsync(input => fetch(`/api/email/${input}`).then(() => /* ... */)), { 
    buffer: 10, // default 1 - tells how many inputs with their respective result are cached
    itemExpiryInMs: 30_000  // default 5_000
  })
)
fabian-hiller commented 1 week ago

Great idea! What is buffer doing? We could work on memoize while also working on a debounce function.

GregOnNet commented 1 week ago

Oh, yeah buffer… I thought it would be handy to be able to tell how many items are cached...

Example:

  1. Someone types gregor@domain.de which triggers an API call from the async validator
  2. Then someone corrects this to gregor@domain.uk which is calling the API again
  3. Finally, someone switches back to gregor@domain.de which is not calling the API because the outcome of the validation is still cached and not outdated.

I hope clarifies the use-case a bit better.

I also like the idea of having debounce for certain values. 💪🏻

GregOnNet commented 1 week ago

After writing the example above, I started thinking if we are talking about cache & cacheAsync instead of Memoization…

fabian-hiller commented 6 days ago

I posted this issue on X to get more feedback and ideas from other users. I am currently focusing on Valibot v1 and Standard Schema and think I will work on this issue after our stable v1 is out.