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

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

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