Skip to content

Commit

Permalink
feat: useStorage update onFocus (#1316)
Browse files Browse the repository at this point in the history
* update storage on focus

* add focus
  • Loading branch information
tlgimenes authored May 24, 2022
1 parent ab3e45f commit c9874d4
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion packages/sdk/src/storage/useStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* between server/browser. When state is 'hydrated', the value in the heap
* is the same as the value in IDB
*/
import { useState, useEffect } from 'react'
import { useEffect, useState } from 'react'
import { get, set } from 'idb-keyval'

const getItem = async <T>(key: string) => {
Expand Down Expand Up @@ -49,10 +49,20 @@ export const useStorage = <T>(key: string, initialValue: T | (() => T)) => {
}
}

const focusHandler = () => {
if (document.visibilityState === 'visible') {
effect()
}
}

setTimeout(effect, 0)
document.addEventListener('visibilitychange', focusHandler)
window.addEventListener('focus', focusHandler)

return () => {
cancel = true
document.removeEventListener('visibilitychange', focusHandler)
window.removeEventListener('focus', focusHandler)
}
}, [key])

Expand Down

1 comment on commit c9874d4

@vercel
Copy link

@vercel vercel bot commented on c9874d4 May 24, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.