'Using AWS clients at the global level in React?

A lot of the AWS API for Javascript relies on creating new AWS objects. For example, the S3 interface relies on creating an AWS object:

AWS.config.apiVersions = {
  s3: '2006-03-01',
  // other service API versions
};

var s3 = new AWS.S3();

It seems one needs to do this to send API requests to AWS services. However, I'm not sure how best to integrate this in React without creating new objects for every different kind of request; this seems very expensive. Is there a way of re-using the same AWS object for many different requests?



Solution 1:[1]

"I'm not sure how best to integrate this in React"

The best way to use the AWS SDK for JavaScript in a React app is to use version 3 and use Async Service Client calls. Your code is not version 3. The Service Client for V3 is S3Client.

Here is V3 JS code that uses Amazon S3 calls in a React app.

import React, { useState } from "javascriptv3/example_code/reactnative/App";
    import { Button, StyleSheet, Text, TextInput, View } from "react-native";
    
    import {
      S3Client,
      CreateBucketCommand,
      DeleteBucketCommand,
    } from "@aws-sdk/client-s3";
    import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity";
    import { fromCognitoIdentityPool } from "@aws-sdk/credential-provider-cognito-identity";
    
    const App = () => {
      const [bucketName, setBucketName] = useState("");
      const [successMsg, setSuccessMsg] = useState("");
      const [errorMsg, setErrorMsg] = useState("");
    
      // Replace REGION with the appropriate AWS Region, such as 'us-east-1'.
      const region = "REGION";
      const client = new S3Client({
        region,
        credentials: fromCognitoIdentityPool({
          client: new CognitoIdentityClient({ region }),
          // Replace IDENTITY_POOL_ID with an appropriate Amazon Cognito Identity Pool ID for, such as 'us-east-1:xxxxxx-xxx-4103-9936-b52exxxxfd6'.
          identityPoolId: "IDENTITY_POOL_ID",
        }),
      });
    
      const createBucket = async () => {
        setSuccessMsg("");
        setErrorMsg("");
    
        try {
          await client.send(new CreateBucketCommand({ Bucket: bucketName }));
          setSuccessMsg(`Bucket "${bucketName}" created.`);
        } catch (e) {
          setErrorMsg(e);
        }
      };
    
      const deleteBucket = async () => {
        setSuccessMsg("");
        setErrorMsg("");
    
        try {
          await client.send(new DeleteBucketCommand({ Bucket: bucketName }));
          setSuccessMsg(`Bucket "${bucketName}" deleted.`);
        } catch (e) {
          setErrorMsg(e);
        }
      };
    
      return (
        <View style={styles.container}>
          <Text style={{ color: "green" }}>
            {successMsg ? `Success: ${successMsg}` : ``}
          </Text>
          <Text style={{ color: "red" }}>
            {errorMsg ? `Error: ${errorMsg}` : ``}
          </Text>
          <View>
            <TextInput
              style={styles.textInput}
              onChangeText={(text) => setBucketName(text)}
              autoCapitalize={"none"}
              value={bucketName}
              placeholder={"Enter Bucket Name"}
            />
            <Button
              backroundColor="#68a0cf"
              title="Create Bucket"
              onPress={createBucket}
            />
            <Button
              backroundColor="#68a0cf"
              title="Delete Bucket"
              onPress={deleteBucket}
            />
          </View>
        </View>
      );
    };
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        alignItems: "center",
        justifyContent: "center",
      },
    });
    
    export default App;

To learn how to successfully setup the AWS SDK for JavaScript in a React app, see this doc topic:

Getting started in React Native

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1