Lodash - Optional Memoize

Viewed 323

Is it possible to avoid getting results from cache when calling a function wrapped in lodash _.memoize()?

For example

import { memoize } from "lodash";

export const getUserPost = memoize(
  async (userId, postId) => {
    const postRef = firestore
      .collection("posts")
      .doc(userId)
      .collection("userPosts")
      .doc(postId);

    const postDoc = await postRef.get();
   
    ...

    return parseUserPost(postDoc);
  },
  (userId, postId) => `[${userId},${postId}]`
);

If I call getUserPost("raul", "postId") I will always be getting cached result if they are in cache...

Is it possible to use the memoize method with some kind of argument to get from the server instead?

Something like

getUserPost("raul", "postId", { cached: false });
1 Answers

By default _.memoize() uses the 1st parameter (userId in your case) as the key in in the memoization cache, or it uses a resolver, like the on you supplied:

(userId, postId) =>`[${userId},${postId}]`

You can delete that key from the cache, when you don't want to a specific value to return the same result:

Example:

const fn = _.memoize(x => x + Math.ceil(Math.random() * 1000))

console.log(fn(1))
console.log(fn(1))
fn.cache.delete(1) // remove a paremter from the cache
console.log(fn(1))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Related