简体   繁体   中英

How to useEffect when value in localStorage changed?

In my react app i'm saving user data filters into localStorage. I want to useEffect, when that data was changed. How to correctly trigger that effect? I tried this:

useEffect(() => {
    if (rawEstateObjects.length && localStorage.activeEstateListFilter) {
      const activeFilter = JSON.parse(localStorage.activeEstateListFilter)
      if (activeFilter.length) {
        applyFilter(activeFilter)
      }
    }
  }, [rawEstateObjects, localStorage.activeEstateListFilter])

but localStorage.activeEstateListFilter doesn't triggers the effect..

did you set value in localStorge? if set it then:

useEffect(() => {
  function activeEstateList() {
    const item = localStorage.getItem('activeEstateListFilter')

    if (rawEstateObjects.length && item) {
      const activeFilter = JSON.parse(localStorage.activeEstateListFilter)
      if (activeFilter.length) {
        applyFilter(activeFilter)
      }
    }
  }

  window.addEventListener('storage', activeEstateList)

  return () => {
    window.removeEventListener('storage', activeEstateList)
  }
}, [])

refrence answer: https://stackoverflow.com/a/61178371/7962191

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM