I'm aiming to update the data in the database but every time I send the data with useState it sends blank data. Also, as I don't understand, when I print the firebase information to the console, it appears as 1 added. So it looks up-to-date but not in the database. What is the reason for this?
export default postDetails = ({navigation, route}) => {
const levelColl = firestore().collection('Level');
const [levelData,setLevelData] = useState([]);
function StoreLevelData (){
levelColl
.doc(user)
.get()
.then(documentSnapshot=>{
data=documentSnapshot.data();
labels=data.levelList.labels;
data1=data.levelList.data;
console.log(data)
let levelList1=[];
for (let index = 0; index < labels.length; index ) {
//console.log(labels[index],data[index])
if(labels[index] == 'araba'){
data1[index] =0.0051
console.log(data1[index])
}
levelList1.push({
levelList:{
labels:[labels[index]],
data:[data1[index]]
}
})
}
console.log(levelList1)
setLevelData(levelList1)
})
}
levelColl
.doc(user)
.set({
levelData})
useEffect(() => {
StoreLevelData();
} , []);
CodePudding user response:
You cannot set the state and then immediately access the new data, because in react setState is asynchronous. In order for you to access the newly set state data, you will have to wait for the next re-render. So in your case the best this to do is to create a new function below like
const updateLevelList = (levelListData) => {
setLevelData(levelListData) // Update the state here
levelColl.doc(user)
.set({
levelListData // Use the same function arg instead of using state
})
}
And the call this function where you used to set the state, ie replace setLevelData(levelList1)
with updateLevelList(levelList1)