Skip to content

Instantly share code, notes, and snippets.

@beabetterdevv
Created October 30, 2021 17:40
Show Gist options
  • Save beabetterdevv/6778b696e31e653614a0117359fb76a0 to your computer and use it in GitHub Desktop.
Save beabetterdevv/6778b696e31e653614a0117359fb76a0 to your computer and use it in GitHub Desktop.
lambda function
----
exports.handler = async (event) => {
console.log(event)
const customerId = event.pathParameters.customerId;
const customer = {'customerId': customerId, 'customerName': "Customer " + customerId };
const response = {
statusCode: 200,
// Uncomment below to enable CORS requests
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*"
},
body: JSON.stringify(customer),
};
return response;
};
index.js
---
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import Amplify from "aws-amplify";
import awsExports from "./aws-exports";
Amplify.configure(awsExports);
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
app.js
---
import logo from './logo.svg';
import './App.css';
import Amplify, { API } from 'aws-amplify'
import React, { useEffect, useState } from 'react'
const myAPI = "YOUR API HERE"
const path = '/customers';
const App = () => {
const [input, setInput] = useState("")
const [customers, setCustomers] = useState([])
//Function to fetch from our backend and update customers array
function getCustomer(e) {
let customerId = e.input
API.get(myAPI, path + "/" + customerId)
.then(response => {
console.log(response)
let newCustomers = [...customers]
newCustomers.push(response)
setCustomers(newCustomers)
})
.catch(error => {
console.log(error)
})
}
return (
<div className="App">
<h1>Super Simple React App</h1>
<div>
<input placeholder="customer id" type="text" value={input} onChange={(e) => setInput(e.target.value)}/>
</div>
<br/>
<button onClick={() => getCustomer({input})}>Get Customer From Backend</button>
<h2 style={{visibility: customers.length > 0 ? 'visible' : 'hidden' }}>Response</h2>
{
customers.map((thisCustomer, index) => {
return (
<div key={thisCustomer.customerId}>
<span><b>CustomerId:</b> {thisCustomer.customerId} - <b>CustomerName</b>: {thisCustomer.customerName}</span>
</div>)
})
}
</div>
)
}
export default App;
@johnyarbi
Copy link

After some trial and error, I was able to get this working with the latest/current version of Amplify (Gen 2).

See AWS Amplify Dev Center - Set up Amplify REST API for the example I referenced.

Here are the changes I made to the author's original index.js and App.js:

index.js

Replace line 6:
import Amplify from "aws-amplify";
with a slightly modified version using curly braces:
import { Amplify } from "aws-amplify";

App.js

Replace the older style API import on line 3:
import Amplify, { API } from 'aws-amplify'
with the newer get() method:
import { get } from 'aws-amplify/api';

Replace the getCustomer() function on lines 14-27:

function getCustomer(e) {
    let customerId = e.input
    API.get(myAPI, path + "/" + customerId)
       .then(response => {
         console.log(response)
         let newCustomers = [...customers]
         newCustomers.push(response)
         setCustomers(newCustomers)

       })
       .catch(error => {
         console.log(error)
       })
  }

with a version that uses the new get() method:

  async function getCustomer(e) {
    let customerId = e.input
    const restOperation = get({apiName: myAPI, path: path + "/" + customerId})
    const { body } = await restOperation.response;
    const response = await body.json();
    console.log(response)
    let newCustomers = [...customers]
    newCustomers.push(response)
    setCustomers(newCustomers)
  }

Another thing that got me was using the wrong value for myAPI. I originally pulled the first part of the API URL and it threw the following error when I tried to click the button to submit a customerId:

API name is invalid.
InvalidApiName: API name is invalid.

I found the correct value in \amplify\#current-cloud-backend\backend-config.json under the "api" key (line 3 for me).

Also, I'm probably the only dummy that copied the code and somehow skipped that line of App.js. I was getting the following error until I realized what was going on:

export 'default' (imported as 'App') was not found in './App' (module has no exports)

Don't forget the last line of App.js:
export default App;

Hope this help!

@eskieclunge
Copy link

@johnyarbi Super Super helpful.

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment