skip to Main Content

I don’t know why it’s not working in Next.js, but it still works normally in another templates.

let subTotal = 0

    if (selectedProducts?.length) {
        for (let id of selectedProducts) {
            const price = products.find(product => product.id === id).price
            subTotal += price
        }
    }

Here my GitHub code: e-commerce

I’ve tried everything that i know, please i need help, tysm.

2

Answers


  1. Presumably products.find(product => product.id === id) isn’t returning an object in at least one iteration of the loop. Maybe include a little defensive coding to ensure that price is available.

    for (let id of selectedProducts) {
    
      // Get the object first
      const product = products.find(product => product.id === id);
    
      // If the product exists AND the price exists on the object
      // add it to the subtotal
      if (product?.price) subTotal += product.price;
    }
    

    For example:

    const products = [
      { id: 1, name: 'potato', price: 2 },
      { id: 2, name: 'fish', price: 12 },
      { id: 3, name: 'gammon', price: 22 },
      { id: 4, name: 'radish', price: 1 }
    ];
    
    const selectedProducts = [1, 3, 6];
    
    let subtotal = 0;
    
    for (const id of selectedProducts) {
      const product = products.find(product => product.id === id);
      if (product?.price) subtotal += product.price;
    }
    
    console.log(subtotal);

    Additional documentation

    Login or Signup to reply.
  2. Inside useEffect set the loading state inside then block to make sure you set the loading state right after async data fetching

    useEffect(() => {
        fetch("https://fakestoreapi.com/products", {
          next: {
            revalidate: 60,
          },
        })
          .then((res) => res.json())
          .then((json) => {
            setProducts(json);
            setLoading(false);
          });
        // ---- NOT HERE -----
        // setLoading(false);
      }, []);
    

    then calculate the subTotal after loading==false

     let subTotal = 0;
      if (!loading && selectedProducts?.length) {
        for (let id of selectedProducts) {
          const price = products.find((product) => product.id === id).price;
          subTotal += price;
        }
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search