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

266
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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