Skip to content

make time cache key less likely to collide with real keys - #45

Merged
jperasmus merged 2 commits into
jperasmus:mainfrom
mmkal:patch-1
Sep 9, 2025
Merged

make time cache key less likely to collide with real keys#45
jperasmus merged 2 commits into
jperasmus:mainfrom
mmkal:patch-1

Conversation

@mmkal

@mmkal mmkal commented Sep 8, 2025

Copy link
Copy Markdown
Contributor

I noticed that you can break the swr behaviour by using a key ending in _time.

Example:

const swr = createStaleWhileRevalidateCache({
    minTimeToStale: 5000,
    storage,
})

const getRandom = async () => {
    await new Promise(resolve => setTimeout(resolve, 20))
    return Math.random()
}

const log = ({value, ...rest}) => {
    console.log(value, JSON.stringify(rest))
}

await swr('test', getRandom).then(log)
await swr('test_time', getRandom).then(log)
await swr('test', getRandom).then(log)
await new Promise(resolve => setTimeout(resolve, 1000))
await swr('test', getRandom).then(log)

This just makes this less likely to happen by mistake

I noticed that you can break the swr behaviour by using a key ending in `_time`.

Example:

```js
const swr = createStaleWhileRevalidateCache({
    minTimeToStale: 5000,
    storage,
})

const getRandom = async () => {
    await new Promise(resolve => setTimeout(resolve, 20))
    return Math.random()
}

const log = ({value, ...rest}) => {
    console.log(value, JSON.stringify(rest))
}

let start = Date.now()
const b4 = () => console.log(`Starting after ${(Date.now() - start) / 1000}s`)

b4()
await swr('test', getRandom).then(log)
await swr('test_time', getRandom).then(log)
await swr('test', getRandom).then(log)
await new Promise(resolve => setTimeout(resolve, 1000))
await swr('test', getRandom).then(log)
```
@jperasmus

Copy link
Copy Markdown
Owner

Thanks, this looks like a more sensible SWR cache key suffix. If you fix the Prettier formatting issue, I'd be happy to merge this in (assuming the build passes after that).

@mmkal

mmkal commented Sep 9, 2025

Copy link
Copy Markdown
Contributor Author

Did the fix by hand 😬

Looks green now. Thanks for the great lib btw!

@jperasmus
jperasmus merged commit d53175b into jperasmus:main Sep 9, 2025
3 checks passed
@jperasmus

Copy link
Copy Markdown
Owner

Thanks for your fix! I'm glad you're getting some value from the lib.

@jperasmus

Copy link
Copy Markdown
Owner

Now available as v3.4.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants