logo oujood
🔍

💾 Sauvegarde du panier avec localStorage

OUJOOD.COM

📦 0. Introduction

Dans ce chapitre, tu vas apprendre à :

  • 📦 Sauvegarder le contenu du panier dans le navigateur
  • 🔁 Restaurer automatiquement le panier au rechargement de la page
  • ✅ Garantir une expérience utilisateur fluide et continue

📦 1. Classe Produit

📋 Copier le code

class Produit {
constructor(id, nom, prix, stock, description) {
this.id = id;
this.nom = nom;
this.prix = prix;
this.stock = stock;
this.description = description;
}
}

🧠 2. Classe Panier avec `localStorage` intégré

📋 Copier le code

class Panier {
constructor() {
const sauvegarde = localStorage.getItem("monPanier");
this.elements = sauvegarde ? JSON.parse(sauvegarde) : [];
this.actualiserAffichage();
}

sauvegarder() {
localStorage.setItem("monPanier", JSON.stringify(this.elements));
}

ajouterProduit(produit) {
const ligne = this.elements.find(p => p.produit.id === produit.id);
const alerte = document.getElementById("alerte");
alerte.textContent = "";

if (ligne) {
  if (ligne.quantite >= produit.stock) {
	alerte.textContent = \`❌ Stock insuffisant pour \${produit.nom}\`;
	return;
  }
  ligne.quantite++;
} else {
  if (produit.stock < 1) {
	alerte.textContent = \`❌ Produit \${produit.nom} en rupture de stock\`;
	return;
  }
  this.elements.push({ produit, quantite: 1 });
}

this.sauvegarder();
this.actualiserAffichage();
}

changerQuantite(id, operation) {
const ligne = this.elements.find(p => p.produit.id === id);
if (!ligne) return;

const alerte = document.getElementById("alerte");
alerte.textContent = "";

if (operation === "plus") {
  if (ligne.quantite >= ligne.produit.stock) {
	alerte.textContent = \`❌ Stock max atteint pour \${ligne.produit.nom}\`;
	return;
  }
  ligne.quantite++;
} else if (operation === "moins") {
  if (ligne.quantite > 1) {
	ligne.quantite--;
  } else {
	this.retirerProduit(id);
	return;
  }
}

this.sauvegarder();
this.actualiserAffichage();
}

retirerProduit(id) {
if (!confirm("Confirmer la suppression du produit ?")) return;
this.elements = this.elements.filter(p => p.produit.id !== id);
this.sauvegarder();
this.actualiserAffichage();
}

total() {
return this.elements.reduce((t, l) => t + l.produit.prix * l.quantite, 0);
}

actualiserAffichage() {
const zone = document.getElementById("liste-produits");
const totalZone = document.getElementById("total");
zone.innerHTML = "";

if (this.elements.length === 0) {
  zone.innerHTML = "<p>Panier vide</p>";
  totalZone.textContent = "0 €";
  return;
}

this.elements.forEach(ligne => {
  const div = document.createElement("div");
  div.innerHTML = \`
	<p>
	  <strong>\${ligne.produit.nom}</strong> - \${ligne.produit.prix.toFixed(2)} € × \${ligne.quantite}
	  <button onclick="monPanier.changerQuantite(\${ligne.produit.id}, 'moins')">➖</button>
	  <button onclick="monPanier.changerQuantite(\${ligne.produit.id}, 'plus')">➕</button>
	  <button onclick="monPanier.retirerProduit(\${ligne.produit.id})">❌</button>
	</p>
  \`;
  zone.appendChild(div);
});

totalZone.textContent = this.total().toFixed(2) + " €";
}
}

🚀 3. Initialisation

📋 Copier le code

const monPanier = new Panier();

📌 Résumé

  • Les données du panier sont stockées dans localStorage sous forme JSON
  • Au chargement de la page, les données sont restaurées automatiquement
  • Chaque modification (ajout, retrait, quantité) déclenche une sauvegarde

🧭 Prochaine étape

Dans le prochain chapitre, nous allons commencer à **ajouter du style CSS minimal** pour rendre l’application plus agréable visuellement.

Souhaites-tu passer au Chapitre 8 du Module 3 : Ajout du style CSS au panier ?