I'm trying to fetch data from firebase Realtime Database and put it into the store. Fetching data from Firebase has no problem. It works fine.
The problem is that the thunk is fulfilled even before data being fetched.
I first tried the code below but the returned 'result' was undefined because it had been assigned even before the onValue was finished.
export const fetchJournals = createAsyncThunk(
'journals/fetchJournals',
(userId) => {
let result;
const query = ref(db, `users/${userId}/journals`);
onValue(query, (snapshot) => {
result = snapshot.val();
})
return result;
}
);
So I tried another code like below using then but got this error code : Object(...)(...).then is not a function
const initialState = { posts: [], status: 'idle', error: null };
export const fetchJournals = createAsyncThunk(
'journals/fetchJournals',
(userId) => {
let result;
const query = ref(db, `users/${userId}/journals`);
onValue(query, (snapshot) => {
return snapshot.val();
}).then((res) => (result = res));
return result;
}
);
export const journalsSlice = createSlice({
name: 'journals',
initialState,
reducers: {},
extraReducers(builder) {
builder
.addCase(fetchJournals.fulfilled, (state, action) => {
state.posts = action.payload;
})
},
});
As far as I know (and I tried and failed), you can't change the state in creatAsyncThunk and should update it with addCase, I'm stuck and need help to update state after all the fetching to be finished.