Home > Back-end >  why does .map() log out the array correctly the first time but say 'undefined' the second
why does .map() log out the array correctly the first time but say 'undefined' the second

Time:12-03

`

export default async function handler(req, res) {
    if (req.method === 'POST') {
        try {
            const bodyItems = req.body.items;
            console.log(bodyItems)
            
            const renderCartItems = bodyItems?.map( singleProduct => {
                return {
                    price_data: {
                        currency: 'usd',
                        product_data: {
                            name: singleProduct.name
                        },
                        unit_amount: singleProduct.price
                    },
                    quantity: singleProduct.qty,
                }
            })
            console.log(renderCartItems, "mapped")
            
            // Create Checkout Sessions from body params.
            const session = await stripe.checkout.sessions.create({
                line_items: renderCartItems,
                
                mode: 'payment',
                success_url: `http://localhost:3000/done`,
                cancel_url: `http://localhost:3000`,
            });
            console.log(session.url)
            res.redirect(303, session.url); 
        } catch (err) {
            res.status(err.statusCode || 500).json(err.message);
        }
    } else {
        res.setHeader('Allow', 'POST');
        res.status(405).end('Method Not Allowed');
    }
}

`

this is the error

"The `line_items` parameter is required in payment mode."

and this is what got consoled out from my consonle.log statments

[
  {
    name: 'sped',
    qty: 1,
    price: 5000,
    img: { _type: 'image', asset: [Object] },
    ogprice: 5000
  }
]
[
  {
    price_data: { currency: 'usd', product_data: [Object], unit_amount: 5000 },
    quantity: 1
  }
] mapped

undefined
undefined mapped

Anybody know how to fix this problem? It seems to get the right data on the first run, but on the second one it returns undefined. I tried using react strict mode but it still runs twice

CodePudding user response:

It looks like the map function is being called on bodyItems twice, but the second time bodyItems is undefined, resulting in renderCartItems also being undefined.

To fix this, you could check if bodyItems is defined before calling map on it, like this:

const renderCartItems = bodyItems ? bodyItems.map(singleProduct => {
  // Code to map the items goes here
}) : [];

This way, renderCartItems will always be an array, even if bodyItems is undefined.

Alternatively, you could avoid calling map on bodyItems twice by using a temporary variable to store the result of the first map call, like this:

const mappedBodyItems = bodyItems.map(singleProduct => {
  // Code to map the items goes here
});
const renderCartItems = mappedBodyItems;

This way, you only call map once, and renderCartItems will always have the correct value.

CodePudding user response:

Taking a step back, the log output your shared appears to indicate your handler is running twice, once with req.body.items as you expect, and once where that's undefined.

I'd suggest adding logging at the start of handler to understand what this extra request is, and also examine your browser network logs to see if the endpoint is being called twice in the client-side code. You might find this is a React error where you're calling your API with unstable data when you don't intend to.

  • Related