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

149
Visualizações
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 Respostas
Responde à pergunta

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