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

177
Visualizações
React axios await dispatch in UseEffect

I need to wait for my axios action to dispatch before continuing in UseEffect

import { getBrief } from '../../store/actions/agency-brief'
import agencyBriefReducer from '../../store/reducers/agency-brief-reducer'

    const [agencyBrief, dispatch] = useReducer(agencyBriefReducer, [])
    
          useEffect(async () => {   
            await getBrief(briefId)(dispatch);
            console.log('BRIEF', agencyBrief)
          }, [])

So console log here is undefined, I need to wait before

action:

export const getBrief = (briefID) => async (dispatch) => {
    try {
        let res = await axiosInstance.get(`/agency_briefs/reactGetBrief/${briefID}`)
        console.log('sre', res )
        return dispatch({ 
            type: 'GET_BRIEF', 
            payload: res.data
        }) 
     }
     catch (err) {
         console.error(err);
     }
}

reducer:

const agencyBriefReducer = (state, {payload, type}) => {
    switch (type) {
        case 'GET_BRIEF':
                return {
                    ...state,
                    brief: payload
                }   
        default:
            return state
    }
}

I've tried async / await but it doesn't work, I need to wait so I can use the result to set the state ? Thanks

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

ok, so one of the comments suggested 2 useEffects and that does the trick:

useEffect(() => {   
    getBrief(briefId)(dispatch);
}, [])
 
useEffect(() => {   
  console.log('BRIEF', agencyBrief)
}, [agencyBrief.brief])
about 4 years ago · Juan Pablo Isaza Relatório

0

const [agencyBrief, dispatch] = useReducer(agencyBriefReducer, [])
        
useEffect(async () => {   
  await getBrief(briefId)(dispatch);
  console.log('BRIEF', agencyBrief) // will always console []
}, [])

Start by explaining why the source code does not behave as expected. useEffect(() => {}, []) Since the dependency is an empty array, this method will only be executed once when the page is initialized. In this render, the value of agencyBrief is always [], will not change.

If you want to monitor the change of the result after the await asynchronous request ends, you can do this:

const [agencyBrief, dispatch] = useReducer(agencyBriefReducer, [])
        
useEffect(async () => {   
  await getBrief(briefId)(dispatch);
}, [])

useEffect(() => {
  // Now agencyBrief is the latest value after await async request ends
  console.log('BRIEF', agencyBrief)
}, [agencyBrief])
about 4 years ago · Juan Pablo Isaza Relatório

0

You can achieve it, I hope that would help.

import { getBrief } from '../../store/actions/agency-brief'
import agencyBriefReducer from '../../store/reducers/agency-brief-reducer'

const [agencyBrief, dispatch] = useReducer(agencyBriefReducer, []);

const getBrief = async () => {
  await getBrief(briefId)(dispatch);
}

useEffect(() => {   
  getBrief();
}, [])

useEffect(() => {
  if (agencyBrief) {
    // perform action
  }
}, [agencyBrief]);
about 4 years ago · Juan Pablo Isaza Relatório
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