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

243
Views
el valor no se puede pasar en useReducer

Contexto.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); };

Llamé con éxito a axios.get y la consola registró el valor de los productos y tiene todos los productos, pero cuando intento pasarlo en useReducer e intento registrar el estado, muestra una matriz vacía.

Reductor.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 solo necesita productos para inicializar el estado en el que no se actualizará solo porque actualice los productos con useState;

Y está manteniendo el estado tanto en useState como en useReducer, debe usar solo uno.

si usas useReducer entonces

la estructura de la acción debe {tipo, carga útil}

 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!