skip to Main Content

I have this simple form executed into React page:

import React from 'react';
import { Link } from 'react-router-dom';
import {LambdaClient, InvokeCommand, LogType} from "@aws-sdk/client-lambda"; // ES Modules import

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

  const invoke = async (funcName, payload) => {
    const client = new LambdaClient({});
    const command = new InvokeCommand({
      FunctionName: funcName,
      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 };
  };
   

  return (
      <>
        <form>
          <input
              type='text'
              className='input-newsletter form-control me-2'
              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;
};

I created IAM user with the fallowing permissions:

enter image description here

Do you know how I can call the AWS Lambda code when I submit this simple form with JavaScript aws-sdk?

2

Answers


  1. Listen for onSubmit Event on form by passing function to form tag like this

    <form onSubmit={handleSubmit}>
    

    As you have added type: submit in your button, form submit event will be triggered on form when someone will click that button.

    And you can write handleSubmit like this to invoke the lambda

     const handleSubmit = async (e) => {
        e.preventDefault();
    
        // Validate and process the form data as needed
        const payload = { email: email }; // Customize this payload based on your Lambda function's requirements
    
        // Replace 'YourLambdaFunctionName' with the actual name of your Lambda function
        const { logs, result } = await invokeLambda('YourLambdaFunctionName', payload);
    
        // Handle the Lambda function response as needed
        console.log('Logs:', logs);
        console.log('Result:', result);
      };
    
    Login or Signup to reply.
  2. Try this, Hope it’s working.

    import React, { useState } from 'react';
    import { LambdaClient, InvokeCommand, LogType } from '@aws-sdk/client-lambda';
    
    const FooterOne = ({ footerLight, style, footerGradient }) => {
      const [email, setEmail] = useState('');
    
      const invokeLambda = async (funcName, payload) => {
        try {
          const client = new LambdaClient({});
          const command = new InvokeCommand({
            FunctionName: funcName,
            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 Lambda:', error);
          throw error;
        }
      };
    
      const handleSubmit = async (event) => {
        event.preventDefault();
    
        try {
          const lambdaFunctionName = 'your-lambda-function-name';
    
          const payload = {
            email: email,
            // Include any other data you want to send to the Lambda function
          };
    
          const lambdaResponse = await invokeLambda(lambdaFunctionName, payload);
          console.log('Lambda invocation result:', lambdaResponse);
        } catch (error) {
          console.error('Error submitting form:', error);
        }
      };
    
      const handleEmailChange = (event) => {
        setEmail(event.target.value);
      };
    
      return (
        <>
          <form onSubmit={handleSubmit}>
            <input
              type='text'
              className='input-newsletter form-control me-2'
              placeholder='Enter your email'
              name='email'
              value={email}
              onChange={handleEmailChange}
              required=''
              autoComplete='off'
            />
            <input type='submit' value='Subscribe' data-wait='Please wait...' />
          </form>
        </>
      );
    };
    
    export default FooterOne;
    

    AWS Lambda Permissions

    • lambda:InvokeFunction: Allows invocation of a Lambda function.

    AWS IAM Permissions (for React App)

    • lambda:InvokeFunction: Allows invoking Lambda functions.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search