0

I have this simple form executed into React page:

import React, {useState} from 'react';
import { Link } from 'react-router-dom';
import {LambdaClient, InvokeCommand, LogType} from "@aws-sdk/client-lambda"; // ES Modules import
const { fromTemporaryCredentials } = require("@aws-sdk/credential-providers");


const FooterOne = ({ footerLight, style, footerGradient }) => {

  const AWS = require('aws-sdk');

  AWS.config.update({
    accessKeyId: "YOURKEY",
    secretAccessKey: "YOURSECRET"
  });


  const handleSubmit = async (event) => {
    event.preventDefault();

    const credentials = await fromTemporaryCredentials({
      params: {
        RoleArn: "arn:aws:lambda:us-east-1:123456789:function:email-submit",
      },
      clientConfig: {
        region: 'us-west-2',
      },
    })();

    try {
      const client = new LambdaClient({
        region: 'us-west-2',
        credentials,
      });

      const command = new InvokeCommand({
        FunctionName: "email-submit",
        Payload: JSON.stringify("payload"),
        LogType: LogType.Tail,
      });

      const { Payload, LogResult } = await client.send(command);
      const result = Buffer.from(Payload).toString();
      const logs = Buffer.from(LogResult, "base64").toString();
      return { logs, result };
    } catch (error) {
      console.error('Error invoking function:', error);
      // Handle errors as needed
    }
  };

  return (
      <>
        <form onSubmit={handleSubmit}>
          <input
              type='text'
              placeholder='Enter your email'
              name='email'
              required=''
              autoComplete='off'
          />
          <input
              type='submit'
              value='Subscribe'
              data-wait='Please wait...'
          />
        </form>
      </>
  );
};

export default FooterOne;

Lambda code into AWS Lambda:

export const handler = async (event) => {
  // TODO implement
  const response = {
    statusCode: 200,
    body: JSON.stringify('Hello from Lambda!'),
  };
  return response;
};

Do you know how I can call the AWS Lambda code when I submit this simple form?

1
  • You have all the code there, you just don't know how to invoke it from the form submit. This isn't an AWS Lambda question at all, it's a basic front-end JavaScript question. If you searched for how to call a JavaScript function on a form submit you would have found TONS of examples, like this one: stackoverflow.com/questions/44989121/… Commented Dec 11, 2023 at 0:57

1 Answer 1

0

Your code above does not call handleSubmit() at all. Put a console.log("inside handleSubmit()") to know when it is being invoked, and also console.log() the result from the await axios(....) to know what the response value is (200, 404, 301, 302, 500, ... ???)

If this were me, I would make a few changes to your code above:

import {useState} from 'react';
import axios from 'axios';

const FooterOne = ({ footerLight, style, footerGradient }) => {
  const [emailValue, setEmailValue] = useState('');
  const [loading, setLoading] = useState(false);

  async function logMovies() {
    setLoading(true);
    const response = await axios.post(
      'https://i1xsjzkri4.execute-api.us-east-1.amazonaws.com/default/serverlessAppFunction',
      { email: `${emailValue}` }
    );
    const result = await response.json();
    console.log(result);
    setLoading(false);
  }

  return (
    <div className='newsletter-form position-relative d-block d-lg-flex d-md-flex'>
      <input
        type='text'
        className='input-newsletter form-control me-2'
        placeholder='Enter your email'
        name='email'
        required={true}
        autoComplete='off'
        onChange={setEmailValue}
        value={emailValue}
      />
      <button onClick={logMovies}>
        {loading ? 'Please wait...' : 'Subscribe'}
      </button>
    </div>
  );
};

export default FooterOne;

Changes:

  • useState to hold emailValue
  • useState to hold loading (indicates if an asynchronous action is happening)
  • changed <form> to <div> -- we want the styling but not the behaviour of a FORM
  • text <input> shows value of emailValue text and calls setEmailValue in the onChange event
  • changed submit <input> to a <button>
  • text of the button changes based on value of loading
  • logMovies now sets value of loading
Sign up to request clarification or add additional context in comments.

10 Comments

I edited it. Can you show me how to invoke the POST request when I click submit button?
What is calling logMovies() ? Typically you would call that function from an onClick event on a <button>. I strongly encourage avoiding use of <form> in React since that tag invokes "form submission behavior" in the browser (which people use .preventDefault() to avoid)....but you are better to simply take control of the form process in your React code entirely on your own. Personally I have taken to using react-hook-form almost exclusively.
nothing is calling logMovies(). The code is unfinished.
I updated my answer with changes I would look to make to your original code. I have not tested the above so there might be a few tweaks that need to be made, but directionally it is what I'd be doing.
Unfortunately I have to use AWS SDK because I don't want to use AWS API Gateway. I want to make a direct lambda call. Please see this: stackoverflow.com/questions/43779871/…
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.