'React Native expo referencing old 'ghost state' when refreshed
So I'm developing a react native app using expo and firebase. The component first receives initialData from its parent component, who downloaded it from a firebase server, and sets it as a state. Whenever the user changes the state in the front-end, the code uploads it to the server. useIsMounting() is a custom hook to check if the component is first mounted.
const MyComponent = ({initialData} => {
const [data, setData] = useState<number[]>([])
const isMounting = useIsMounting()
const uploadData = () => {
myUpLoadFunction(data).then(() => {
console.log('upload success, size of data: ' + data.length)
})
}
useEffect(() => {
setData(initialData)
}, [])
useEffect(() => {
if(!isMounting) {
uploadData(data)
}
}, [data])
return(
<View>
...
)
})
The problem is when i make a change to the data in the front-end and refresh the app by saving the code. Instead of just calling uploadData() once, it calls it twice by uploading the current state first, and immediately after that, uploading the old state before the change. Interestingly, this problem does not happen when I reload the app by pressing the reload button in expo go.
For example, let's say initialData was an array of size 5. I then delete one element. And then I refresh the app. This is what my console looks like.
download complete
upload success, size of data: 5 //initial data
upload success, size of data: 4 //after data delete
upload success, size of data: 4 //after refresh
upload success, size of data: 5 //immediately after, uploads the old 'ghost state'
When I check the firebase database after this, the data has changed back to 5 elements. How can I solve this problem?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
