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

251
Views
value is not able to be passed in useReducer

Context.js

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

const Cart = createContext();

const Context = ({ children }) => {
  const [products, getProduct] = useState("");
  useEffect(() => {
    axios.get("/api/products/").then((response) => {
      getProduct(response.data);
    });
  }, []);
  console.log(products);
  const [state, dispatch] = useReducer(cartReducer, {
    products: products,
    cart: [],
  });
  console.log(state);

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

export default Context;

export const cartState = () => {
  return useContext(Cart);
};

I successfully called axios.get and console log the value of products and it has all the products in it, but when I try to pass it in useReducer and try to log the state it shows empty array.

Reducer.js

export const cartReducer = (state, action) => {
  switch (action.type) {
    default:
      return state;
  }
};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

useReducer only need products for initail the state it will be not updated just because you update products with useState;

And you are keeping the state in both useState and useReducer you should be using only one.

if you use useReducer then

action structure should {type,payload}

const [state, dispatch] = useReducer((pervState,action)=>{
    switch(action.type){
        case "setProducts":
            return {...prevState,products:action.payload};
        case "setCart":
            return {...prevState,cart:cart.payload};
        default:
            throw new Error(`unhandled action.type ${action.type}`)
        }
    },{
    products: products,
    cart: [],
  });



  
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!