Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda