Skip to main content

Overview

Tienda ETCA uses two notification systems to provide user feedback:
  • React Toastify: Lightweight toast notifications for cart operations
  • SweetAlert2: Rich modal dialogs for admin actions and confirmations

React Toastify

Toast notifications are used in CartContext for non-intrusive feedback during shopping operations.

Implementation

Import toast from React Toastify in ~/workspace/source/src/context/CartContext.jsx:2:
import { toast } from 'react-toastify';

Adding Products to Cart

When a product is added to the cart, the system shows different messages based on whether the product already exists:
const handleAddToCart = (product) => {
  const productExist = cart.find((item) => item.id === product.id);

  if (productExist) {
    setCart(
      cart.map((item) =>
        item.id === product.id
          ? { ...item, cantidad: item.cantidad + 1 }
          : item
      )
    );
    toast.info(`Cantidad aumentada para "${product.nombre}"`);
  } else {
    setCart([...cart, product]);
    toast.success(`"${product.nombre}" agregado al carrito`);
  }
};
The toast automatically displays the product name in the notification message for better user feedback.

Toast Types

Tienda ETCA uses two toast notification types:

Success Toast

Used when a new product is added to cart
toast.success(`"${product.nombre}" agregado al carrito`);

Info Toast

Used when quantity is increased for existing product
toast.info(`Cantidad aumentada para "${product.nombre}"`);

Usage Example

import { useContext } from 'react';
import { CartContext } from '../context/CartContext';

function ProductCard({ product }) {
  const { handleAddToCart } = useContext(CartContext);
  
  return (
    <button onClick={() => handleAddToCart(product)}>
      Add to Cart
    </button>
  );
}

SweetAlert2

SweetAlert2 provides rich modal dialogs for critical admin operations that require user confirmation.

Implementation

Imported in AdminContext at ~/workspace/source/src/context/AdminContext.jsx:2:
import Swal from 'sweetalert2'

Success Notifications

Used to confirm successful operations:

Product Added

const agregarProducto = async (producto) => {
  try {
    const respuesta = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(producto)
    })
    if (!respuesta.ok) {
      throw new Error('Error al agregar producto')
    }
    const data = await respuesta.json()
    Swal.fire({
      title: "Realizado!",
      text: "Producto agregado correctamente!",
      icon: "success"
    });
    cargarProductos()
  } catch (error) {
    console.log(error.message);
  }
}

Product Updated

Swal.fire({
  title: "Realizado!",
  text: "Producto actualizado correctamente!",
  icon: "success"
});

Confirmation Dialogs

For destructive actions, SweetAlert2 shows a confirmation dialog before proceeding:
const eliminarProducto = async (id) => {
  const result = await Swal.fire({
    title: '¿Estás seguro de eliminar el producto?',
    icon: 'warning',
    showCancelButton: true,
    confirmButtonText: 'Sí, eliminar',
    cancelButtonText: 'Cancelar',
  });

  if (result.isConfirmed) {
    try {
      const respuesta = await fetch(
        `https://681cdce3f74de1d219ae0bdb.mockapi.io/tiendatobe/productos/${id}`, 
        { method: 'DELETE' }
      );
      if (!respuesta.ok) throw new Error('Error al eliminar');

      Swal.fire({
        title: "Realizado!",
        text: "Producto eliminado correctamente!",
        icon: "success",
      });

      cargarProductos();
    } catch (error) {
      Swal.fire({
        title: "Error!",
        text: "Hubo un problema al eliminar el producto!",
        icon: "error"
      });
    }
  }
}
The confirmation dialog prevents accidental deletions by requiring explicit user confirmation.

Alert Types

SweetAlert2 is used with multiple icon types:
Swal.fire({
  title: "Realizado!",
  text: "Producto agregado correctamente!",
  icon: "success"
});

Notification Comparison

React Toastify

Best for:
  • Non-blocking notifications
  • Cart operations
  • Quick feedback
  • Multiple simultaneous messages
Location: CartContext.jsx

SweetAlert2

Best for:
  • Confirmation dialogs
  • Destructive actions
  • Admin operations
  • Detailed error messages
Location: AdminContext.jsx

Best Practices

1

Choose the Right Notification Type

Use toasts for informational messages and SweetAlert2 for actions requiring user confirmation.
2

Include Contextual Information

Always include the product name or relevant details in notification messages.
toast.success(`"${product.nombre}" agregado al carrito`);
3

Handle Errors Gracefully

Show error notifications when operations fail to keep users informed.
Swal.fire({
  title: "Error!",
  text: "Hubo un problema al eliminar el producto!",
  icon: "error"
});
Both notification systems are already configured and available through their respective contexts (CartContext and AdminContext).

Build docs developers (and LLMs) love