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

150
Vistas
useReducer not accepting array or state

unable to pas data (which is array) in initialisation of useReducer hook which contain array of object , Getting result in child component empty array in products initialisation.

I want same data in child component as same I passed.

code :

import React, { createContext, useContext, useEffect, useReducer, useState } from 'react'
import faker from "faker";
import { cartReducer } from './Reducer';

export const Cart = createContext();
const Context = ({ children }) => {

    const [data, setProduct] = useState();

    useEffect(() => {
        var axios = require('axios');

        var config = {
            method: 'get',
            url: '<apicalling here>',
            headers: {
                'Authorization': 'Token xyz'
            }
        };

        axios(config)
            .then(function (response) {
                setProduct(response.data.cart[0].items);

            })
            .catch(function (error) {
                console.log(error);
            });

    }, []);


    console.warn("hello", data); //yes working, data rendering here

    const [state, dispatch] = useReducer(cartReducer, {
        products: data,
        cart: [],
    });

 
    return <Cart.Provider value={{ state, dispatch }}>{children} </Cart.Provider>;
};

export default Context;
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This is happening because the state of your reducer sets before the API call resolves.

And you are getting those updated data in console.log because you are updating it into the data state, but the reducer has access to the same previous data (reason: state of your reducer sets before API call resolves).

So, the solution to your problem is to create one action that dispatches your updated value of Products once you got the response from the API.

import React, { createContext, useContext, useEffect, useReducer, useState } from 'react' import faker from "faker"; import { cartReducer } from './Reducer';

const cartReducer = (state, { type, payload = {} }) => {
switch (type) {
    case 'setProducts': {
     return {...state, products: payload};
    }
    /*
       Other actions
    */
    default: {
      // your default action
    }
  }
}

export const Cart = createContext(); 

const Context = ({ children }) => {

const [data, setProduct] = useState();

useEffect(() => {
    var axios = require('axios');

    var config = {
        method: 'get',
        url: '<apicalling here>',
        headers: {
            'Authorization': 'Token xyz'
        }
    };

    axios(config)
        .then(function (response) {
            setProduct(response.data.cart[0].items);
            dispatch({type: 'setProducts', payload: response.data.cart[0].items}) // <--- dispatch once you get data

        })
        .catch(function (error) {
            console.log(error);
        });

}, []);


console.warn("hello", data); //yes working, data rendering here

const [state, dispatch] = useReducer(cartReducer, {
    products: [],
    cart: [],
});

const value = {
   products: state.products; // <-- access it from state
   cart: state.cart
}

return <Cart.Provider value={value}>{children} </Cart.Provider>; // <--- change value here
};

export default Context;
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