Home > Mobile >  How to update element when localstorage updates without page refresh in react?
How to update element when localstorage updates without page refresh in react?

Time:02-23

When localstorage updates, I am trying to make text of an element change to what localstorage contains. This does work and the element changes when I reload the page, however, I need it so that it updates without reload.

I have heard about useState and useEffect, but due to my limited knowledge I do not know how those would or could be implemented.

Help would be appreciated.

function appers(){
  const { ipcRenderer } = window.require("electron");
  ipcRenderer.send('execMain')

  ipcRenderer.on('exec_details',(e,val)=>{
    let itemzz = val;
    let drops = itemzz.slice(3)
    let dropAPI = JSON.parse(drops)
    let firstItemTitle = dropAPI[0]["item"].toString()
    let firstItemImage = dropAPI[0]["add"].toString()
    let firstItemDate = dropAPI[0]["date"].toString()
    let arr1 = []
    arr1.push(firstItemTitle, firstItemAdd, firstItemDate)
    localStorage.setItem('item1', JSON.stringify(arr1))
  })
}

function MyFunc(){
   let item1Name = JSON.parse(localStorage.getItem('item1'))[0]
   return(
      <div>
        <Button onClick={appers}></Button>
        <p>{item1Name}</p>
      </div>
   )
}

export default MyFunc;

CodePudding user response:

In react you need to have a state for component re-render. Your code structure should be like

//appear function should return the value return arr1

function MyFunc = () => {

const [item1Name , setitem1Name] = useState(null)
   let item1Name = JSON.parse(localStorage.getItem('item1'))[0]

const handleAppearance = () => {
setitem1Name(appear())


}
   return(
      <div>
        <Button onClick={handleAppearance}></Button>
        <p>{item1Name}</p>
      </div>
   )
}

CodePudding user response:

first, you need a state to store your data, you can use useState for that.

it is a hook that allow you to have state variable in functional components

const [data, setData] = useState({
   triggerUpdate: false,
}) 

second, you need as you mention, useEffect. It has multiple functionality but I'll get the one what u need to

useEffect(() => {
   if(data.triggerUpdate) {
      let items = <your data here>
      setData({ items: items, triggerUpdate: false })
   }
}, [triggerUpdate])

the last line in square brackets is dependency array which means useEffect will only trigger any of dependency array variable changes.

if you leave it empty it will only works in first render if you delete dependency array it will work on every render but we don't want it in this case

edit: you can use a boolean value to update your render and set it to false to not to cause infinite render

  • Related