Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!