I am making an expense tracker app using React Native and Back4App (Parse) as backend. I want to fetch all objects under class Transactions in the Parse database and filter them by username. The results are like these,
Array [
Object {
"amount": -350,
"objectId": "hzXdXRj8jf",
"type": "Expense",
"username": "james",
},
Object {
"amount": -200,
"objectId": "r2uDmSZ666",
"type": "Expense",
"username": "james",
},
Object {
"amount": 2000,
"objectId": "FBEGubpwNn",
"type": "Income",
"username": "sheldon",
},
Object {
"amount": -500,
"objectId": "oYam0dUOxu",
"type": "Expense",
"username": "sheldon",
},
]
Since, I am using james account, I want to see results with username james. This the code I use,
const getCurrentUser = async () => {
const user = await Parse.User.currentAsync()
if(user !== null) {
setUsername(user.get('username'))
} else {
Alert.alert("Error!", "Cannot fetch username")
}
}
const readTransactions = async () => {
setLoading(true)
getCurrentUser()
const parseQuery = new Parse.Query("Transactions")
try {
let results = await parseQuery.find()
let json = JSON.parse(JSON.stringify(results))
var filteredJSON = json.filter(it => it.username === username)
console.log(filteredJSON)
setTransactions(filteredJSON)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
return true
} catch (error) {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
}
const onRefresh = () => {
setRefresh(true)
readTransactions()
}
useEffect(() => {
isFocused && readTransactions()
}, [isFocused])
If I reload the app / open the app for first time, it doesn't fetch any results i.e. console.log(filteredJSON) returns Array [].
But upon manually refreshing the flatlist, it returns the correct results
Array []
Array [
Object {
"amount": -350,
"objectId": "hzXdXRj8jf",
"type": "Expense",
"username": "james",
},
Object {
"amount": -200,
"objectId": "r2uDmSZ666",
"type": "Expense",
"username": "james",
},
]
So, the problem is filteredJSON doesn't return any result upon restarting the app but it returns the correct results on refreshing once. But obviously, I want to return the correct data when the user opens the app without manually refreshing.
Even if I use parseQuery.contains('username', username) without using any json filter, the problem still persists.
(If I do setTransactions(json) it fetches the correct results at first chance without any refreshing, but I don't want to do that since it will return all data of various users under Transactions class.)