Firstly, I'm working with React Native. I'm getting a data from Firebase and want to write to store (by Redux) quickly. But It doesn't work. You can find my all of codes below:
Function:
async getTumData (uid) {
const {selectedGroupDetail, getSelectedGroupDetail} = this.props;
var yeniGrupDetayi = {};
await firebase.database().ref("/groups/"+uid).once('value').then(
function(snapshot){
yeniGrupDetayi = {...snapshot.val(), uid: uid};
}).catch(e => console.log(e.message));
console.log("FONKSIYON ICERISINDEKI ITEM ==>", yeniGrupDetayi);
this.props.getSelectedGroupDetail(yeniGrupDetayi);
console.log("ACTION'DAN GELEN ITEM ===>", selectedGroupDetail);
}
Action:
export const getSelectedGroupDetail = (yeniGrupDetayi) => {
return {
type: GET_SELECTED_GROUP_DETAIL,
payload: yeniGrupDetayi
}
};
Reducer:
case GET_SELECTED_GROUP_DETAIL:
return { ...state, selectedGroupDetail: action.payload}
Çıktı:
FONKSIYON ICERISINDEKI ITEM ==> {admin: {…}, groupDescription: "Yaygın inancın tersine, Lorem Ipsum rastgele sözcü…erini incelediğinde kesin bir kaynağa ulaşmıştır.", groupName: "İnsan Kaynakları", groupProfilePic: "", members: {…}, …}
ACTION'DAN GELEN ITEM ===> {}
There is a FlatList in my page and I defined a button in renderItem of FlatList. When i click to this button, getTumData()
function is working.
When i click to this button first time, selectedGroupDetail
is null
. Second time, it shows previous data.
How can i write a data to Store quickly and fast?
Thanks,
The thing is: - You're using both async/await, and then/catch in your code. - you're calling getSelectedGroupDetail before your async code resolves.
Fast Solution
Better Solution:
1st: use Redux-Thunk middleware. 2nd: Move your Async code into your action creator: I mean this
3rd: Your reducer should have another piece of data as an indicator for the time-gap before your selectedGroupDetail resolves:
4th: Inside your action creator, you should dispatch 3 actions: ACTION_NAME_START // This should should only set loading to true in your reducer. ACTION_NAME_SUCCESS // set loading to false, and selectedGroupDetail to the new collection retured ACTION_NAME_FAIL // in case op failed set error
5th: Your React component, should display a loading indicator (spinner or somthing), and maybe disable FlatList button during the loading state.