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.
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])