javascriptreactjsamazon-web-servicesaws-sdkaws-sdk-js

Invoke AWS Lambda into React page using aws-sdk


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?


Solution

  • 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

    AWS IAM Permissions (for React App)