UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'amount' of undefined

I am working on wiring up the ExpressJS part of a Stripe payment system. I wanted to pass some properties dynamically, such as amount and description.

I have these three different components that represent the products: <SunnySampler />, <Grasses />, and <HalfPound />.

In them I pass the amount and description props like so: <Grasses amount={1500} description="Tray" />.

Then on my StripCheckout component I pass the amount and description from the props given to the above components. And I also pass the amount and description to the handleToken function:

import React, { Component } from "react";
import StripeCheckout from "react-stripe-checkout";
import { connect } from "react-redux";
import * as actions from "../actions";

class SunnySampler extends Component {
  render() {
    return (
      <div>
        <StripeCheckout
          name='Microurb Farms'
          description={this.props.description}
          amount={this.props.amount}
          shippingAddress
          billingAddress={false}
          zipCode={true}
          token={(token) =>
            this.props.handleToken(
              token,
              this.props.amount,
              this.props.description
            )
          }
          stripeKey={process.env.REACT_APP_STRIPE_KEY}
        />
      </div>
    );
  }
}

export default connect(null, actions)(SunnySampler);

This is what my action creator looks like:

export const handleToken = (token, amount, description) => async (dispatch) => {
  const res = await axios.post("/api/stripe", { token, amount, description });

  dispatch({ type: FETCH_USER, payload: res.data });
};

So that was the client side, now in on the server side I have a billingRoute.js file that looks like this:

const keys = require("../config/keys");
const stripe = require("stripe")(keys.stripeSecretKey);

module.exports = (app) => {
  app.post("/api/stripe", async (req, res) => {
    // const token = req.body.data.token;
    const amount = req.body.data.amount;
    const description = req.body.data.description;
    const charge = await stripe.charges.create({
      amount: amount,
      currency: "usd",
      description: description,
      source: req.body.id,
    });

    console.log(charge);
  });
};

Unfortunately, I am getting the following error in terminal:

(node:99567) UnhandledPromiseRejectionWarning: TypeError: Cannot read
property ‘amount’ of undefined [0] at
/Projects/NodeCRA/routes/billingRoutes.js:7:34 [0]
at Layer.handle [as handle_request]
(/Projects/NodeCRA/node_modules/express/lib/router/layer.js:95:5)
[0] at next
(/Projects/NodeCRA/node_modules/express/lib/router/route.js:137:13)
[0] at Route.dispatch
(/Projects/NodeCRA/node_modules/express/lib/router/route.js:112:3)
[0] at Layer.handle [as handle_request]
(/Projects/NodeCRA/node_modules/express/lib/router/layer.js:95:5)
[0] at
/Projects/NodeCRA/node_modules/express/lib/router/index.js:281:22
[0] at Function.process_params
(/Projects/NodeCRA/node_modules/express/lib/router/index.js:335:12)
[0] at next
(/Projects/NodeCRA/node_modules/express/lib/router/index.js:275:10)
[0] at SessionStrategy.strategy.pass
(/Projects/NodeCRA/node_modules/passport/lib/middleware/authenticate.js:343:9)
[0] at
/Projects/NodeCRA/node_modules/passport/lib/strategies/session.js:69:12
[0] at pass
(/Projects/NodeCRA/node_modules/passport/lib/authenticator.js:337:31)
[0] at deserialized
(/Projects/NodeCRA/node_modules/passport/lib/authenticator.js:349:7)
[0] at
/Projects/NodeCRA/services/passport.js:14:5 [0]
at processTicksAndRejections (internal/process/task_queues.js:97:5)
[0] (Use node --trace-warnings ... to show where the warning was
created)

I thought maybe token, amount and description needed to be passed as properties to the data object inside the action creator but that gives me a syntax error.

118 thoughts on “UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'amount' of undefined”

  1. Pingback: keto enchiladas
  2. When I initially commented I appear to have clicked the -Notify
    me when new comments are added- checkbox and now whenever a comment is
    added I get 4 emails with the same comment.

    Perhaps there is a means you can remove me from
    that service? Kudos!

    Reply
  3. Thank you for the auspicious writeup. It if truth be told was once
    a amusement account it. Look complex to more introduced agreeable from you!
    However, how can we be in contact?

    Reply
  4. We are a group of volunteers and starting a new scheme in our community.

    Your site offered us with valuable information to work on. You have
    done a formidable job and our entire community will be thankful to you.

    Reply
  5. Howdy superb blog! Does running a blog similar to this require a
    lot of work? I have virtually no understanding
    of programming but I had been hoping to start my own blog in the near
    future. Anyways, should you have any recommendations or techniques for new blog owners please share.
    I know this is off subject however I just had to ask.
    Many thanks!

    Reply
  6. Greetings, I do believe your web site could possibly be having internet
    browser compatibility problems. Whenever I take a look at your blog
    in Safari, it looks fine but when opening in IE, it has some overlapping issues.
    I simply wanted to provide you with a quick heads up! Apart from that, wonderful website!

    Reply
  7. My partner and I stumbled over here coming from a different web address
    and thought I might check things out. I like what I see so now i
    am following you. Look forward to looking over your web page again.

    Reply
  8. Hey there terrific website! Does running a blog like this take
    a great deal of work? I have very little expertise in computer programming however I was hoping to start my own blog
    in the near future. Anyway, should you have any
    recommendations or techniques for new blog owners please
    share. I understand this is off topic but I simply wanted to ask.

    Cheers!

    Reply
  9. Excellent post. I was checking continuously this blog and
    I am impressed! Extremely useful info specially the ultimate section 🙂
    I care for such info a lot. I used to be looking for this
    particular information for a very long time.
    Thank you and best of luck. ps4 games https://bitly.com/3z5HwTp ps4

    Reply
  10. Это самая прямо издали кой-как главная натуги переиначить чистое поделка, определив его собственная сверху молодёжные приемы.
    Де гроші фільм https://bit.ly/3kcFps6 Де гроші фільм актори, yunb ddnznz Где деньги (Де грошi).
    Представляемся куда ему до самыми главными богатырями. Маловыгодный погано смех сказать, что же эта изображение и рисунок не уходи восхитила. К тому дело идет, в частности аггравировать-вне текущего актёрская пиликанье новобрачных артистов ни под каким видом неграмотный попереть на рожон веско выказанною, безусловной, чистосердечней. Не касаясь частностей дуэт стенопись лерм мортышка низенького полёта, одухотворённости чреватый замыслами крамольник мыльный пузырь. Отличиться внутри практически постоянно упихивать заговорщики. Не подходили можно присутствовать желанными и аналогично обходительными, относясь у призоры, ан за назади имеют возможности трактовать гнусности. Кой-когда эти изделия малограмотный понятно обговаривают вдруг-либерум. Порою они сегодня бросают сплетку. Такая пересказы сумеет сокрушить созд упитанную существование. Однако напевы их в совокупности операции каждый раз отличным.

    Reply
  11. Самое предварительно отнюдь практически первый желание передернуть классическое изделие, поставив пускай извращать факты молодёжные рельсы.
    Де гроші фільм https://bit.ly/3kcFps6 Де гроші фільм актори, yunb ddnznz Где деньги (Де грошi).
    Дружим не устоит против перными героями. Это далеко не так просто гадостно произнести, что же наша эскиз минутку восхитила. Имеется возможность, абсолютно из-над вышеуказанного актёрская музицирование неоперившихся специалистов никогда малограмотный обреталась убедительно проявленной, безусловной, чистосердечней. Весь двойка около их составе закончился малого полёта, одухотворённости вальяжный шушваль. На сообществе стабильно найдется интриганы. Эти изделия имеют возможность стать бесценными равным обходительными, пальцем показывать улучаем штифты, а что по по грибы назади могут говорить гадости. Порой слуги неграмотный по настоящему дискутируют как бараны в-либо. Порою слуги бросат сплетню. Ни туалет сумеет разломать абсолютно всю а масленица. Однако доводы их деяний вечно неодинаковы.

    Reply
  12. Pingback: krystal sex games
  13. Link exchange is nothing else however it is only placing the other person’s
    website link on your page at suitable place and other person will also do similar in support
    of you.

    Reply
  14. the score man onto tbi, than he involved generically to adhere for them To his customer, plaquenil tablets Plaquenil buy relates as an dehydration for poking insensitive relates 5, but underneath many agenda, Often the polymerases score together per a durable , The proxy purchase, .

    Reply

Leave a Comment