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

264
Visualizações
How to use Async/Await or Promise in reducer function so that when i initialized my initial state (through axios) , the reducer func. should wait

in the reducer function, I want to initialize the initialState which is first updated by some data through an API call (by Axios) then it will pass through the reducer function.

The problem is when it is being updated by through an API call, the reducer has not taken the updated state, which I came to realize when I access the initialState in a different component, that will show me the very first initialization.

Initial State


    var seriesData = {
        horror:[],
        comedi:[],
        romantic:[]
    }

API call through AXIOS and try to update the initial state


    var gen_typ = ['horror','comedi','romantic']
    
    gen_typ.forEach(elm => {
        axios.get(`${process.env.REACT_APP_SD_API}${elm}`)
        .then((result) => {
            seriesData = {...seriesData,elm:result}
        }).catch((err) => {
            console.log(err);
        });
    });

Reducer function


    export function SD_Operation(state = seriesData,action){
        switch(action.type){
    
            case "GET_MORE":
               return{
               ...state,
              [action.payload.genTyp]:[...state[action.payload.genTyp],action.payload.data]}
            
            default:
                return state;
        }
    }

when I access the initial state in one of my components and console out

inside component


    var Series_data = useSelector(state => state.SD_Operation);
    
    useEffect(()=>{
        console.log('@login page',Series_data) ;
    },[])

output I get

@login page {horror: Array(0), comedi: Array(0), romantic: Array(0)}

comedi: []
horror: []
romantic: []

output I expect

an array of data

{horror: Array(some length), comedi: Array(some length), romantic: Array(some length)}

comedi: [{},{}....]
horror: [{},{}....]
romantic: [{},{}....]
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is a typical scenario, and commonly solved differently:

  1. The initial state for your reducer is simply empty. The data is not there yet when the app loads, so define it accordingly.
  2. Create an async action (using thunk or other middleware) that fetches the API data.
  3. Dispatch this action when your root component mounts (in componentDidMount or via a useEffect with empty dep. array).
  4. Any other selectors and components using this API data needs to take the initial empty state into account.
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