Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

278
Visualizações
How to set item in localSorage in realtime

I'm trying to build a child array nested into a data array, onClick user inputs don't get saved in localStorage in realtime, but

For example there are 4 Buttons with 4 different user input 1,2,3,4 If the user clicks on 1, later click on 2 then the input of choice 1 gets into local storage, which means my function doesn't set it in real-time until the user clicks the next event or twice.

Related states

const deviceReport = localStorage.getItem('deviceReport') ? JSON.parse(localStorage.getItem('deviceReport')) : []  // this is in the parent component
const [data, setData] = useState(deviceReport) // this one placed in parent component and I'm passing in child component as parameter. 
const [childData, setChildData] = useState([]

) // That state is placed in the child component

childArrayHandler

const childArrayHandler = (sub, questionId) => {
    const hasId = childData.find(({ id }) => sub.id === id)
    // copy data to mutable object

    if (!hasId) {
      let newData = [...childData]
      newData = [...newData, { id: sub.id, sub_question: sub.sub_question, weightage: sub.weightage }]
      setChildData(newData)
    }
    //  find parent of the child
    const parent = data.find(({ parentId }) => questionId === parentId)
    // find index of parent
    const indexOfParent = data.indexOf(parent)
    // update data with child related to parent
    let newData = [...data]
    newData[indexOfParent].child = childData
    localStorage.setItem('deviceReport', JSON.stringify(newData)) // Here is a issue , 
    onDataChange(newData) // Updating the data in parent component state of data
  }

I want to update deviceReport which is in the localStorage, using the childArrayHandler function This line

localStorage.setItem('deviceReport', JSON.stringify(newData))

Dosnt updated the storage in realtime and until user presses twice or click on another button in the option. Please help me to fix this.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think the localStorage.setItem is synchronized; thus, it will update your state in real-time. However, it may not be correctly recalculated, for it is not a state in react.

To prevent this, you can use useLocalStorageState hook in ahooks instead of setting it manually:

https://ahooks.js.org/hooks/use-local-storage-state


If you want to manage the state in localstorage manually, you can do something like this:

const [deviceReport, setDeviceReport] = useState([]);

// Try to retrieve from localstorage on init
useEffect(() => {
  try {
    let tmp = JSON.parse(localStorage.getItem('deviceReport'))
    setDeviceReport(tmp);
  } catch {
  }
}, [])

// Set to localstorage when deviceReport change
useEffect(() => {
  localStorage.setItem('deviceReport', JSON.stringify(deviceReport))
}, [deviceReport])
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda