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

243
Vistas
What is the best way to call a function and render a child component onClick in React?

I have the below code, I want to call a function and render a child component onCLick. What is the best way to achieve this?

import AddOrder from './AddOrder'

return (
<Button onClick={handleCheckout}>Checkout</Button>
)

const handleCheckout = () => {
        <AddOrder />
        fetch("http://localhost:5000/create-checkout-session", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                items: data?.getUser ? data.getUser.cart : cart,
                email: currentUser ? currentUser.email : undefined,
            }),
        })
            .then(async (res) => {
                if (res.ok) return res.json();
                const json = await res.json();
                return await Promise.reject(json);
            })
            .then(({ url }) => {
                window.location = url;
            })
            .catch((e) => {
                console.error(e.error);
            });
    };

I tried making a new function called handleAll and adding it like this:

function handleAll(){
   handleCheckout()
   <AddOrder />
}

AddOrder.js:

function AddOrder() {
  const d = new Date();
  let text = d.toString();
  const { currentUser } = useContext(AuthContext);
  
  const { data, loading, error } = useQuery(queries.GET_USER_BY_ID, {
    fetchPolicy: "cache-and-network",
    variables: {
        id: currentUser.uid
    },
});
const [addOrder] = useMutation(queries.ADD_ORDER); 
useEffect(() => {
    console.log('hi')
})
if(error) {
    return <h1> error</h1>;
   }
   
if(loading) {
    return <h1> loading</h1>;
   }
if (data){
let newCart = []
for(let i=0; i< data.getUser.cart.length; i++){
    newCart.push({quantity: data.getUser.cart[i].quantity, _id: data.getUser.cart[i]._id})
}
console.log(newCart)
  addOrder({
    variables: {
        userId: currentUser.uid, status: 'ordered', createdAt: text, products: newCart
    }
  });
  console.log("hello")
}
}
export default AddOrder;

This did not work either. When I reload this it add 3 copies of the same order to the mongodb collection. What is the right way to do this?

about 4 years ago · Juan Pablo Isaza
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