Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

158
Vistas
Redux thunk returns value before fetching data

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.

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda