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

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

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