How to cache values?
See original GitHub issueI’m trying to implement caching: If a value doesn’t exist, then fetch it.
const cache = atom({
key: "cache",
default: new Map()
});
const value = selectorFamily({
key: "value",
get: (id) => async ({ get }) => {
const map = get(cache);
return map.get(id) || await fetch(id);
},
});
My questions are:
- Can I force a re-fetch without manually fetching and setting in my component? I tried adding a setter:
set: (id) => async ({ set }) => {
const data = await fetch(id);
set(cache, (prevState) => prevState.set(id, data));
},
with the idea of just calling useResetRecoilState(value(id))
. But, this doesn’t seem to update my components. Is this because set is async?
- How do I initially populate the cache? I can call
set
for the IDs I care about, but ideally I wantget
to add values to the cache.
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (3 by maintainers)
Top Results From Across the Web
What is Caching and How it Works - AWS
A cache is a high-speed data storage layer which stores a subset of data, typically transient in nature, so that future requests for...
Read more >Recommended initial cache values - Sitecore Documentation
Role Cache Initial value
Content Delivery Prefetch (web database) 1000 MB
Content Delivery Data (web database) 1000 MB
Content Delivery Item (web database) 1000 MB
Read more >What Is Caching and How It Works - Fortinet
Cached data works by storing data for re-access in a device's memory. The data is stored high up in a computer's memory just...
Read more >Modern Caching 101: What Is In-Memory Cache, When and ...
Some caches are based on a key-value store. This essentially means you can provide the data store a unique key and it will...
Read more >What Is Cached Data? Why & How Should You Clear It? - Okta
Cached data is information stored on your computer or device after you visit a website. Developers use cached data to improve your online...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Duplicate of #290
Ah, so your usecase is to return the previous value while pending. the
useTransition()
hook may be useful for this when Recoil releases full concurrent mode support. In the meantime, #290 discusses some current workarounds.JS
Map
is mutable, so you should not callset()
on aMap
stored in an atom. Atom state isn’t really meant to be used for holding caches like this. It looks like you’re trying to use a cache to cache the results of theselectorFamily()
evaluation? If so, that shouldn’t be necessary since Recoil already caches selector evaluations.