I am trying to call an external API using the fetch method (basic authentication) but the code freezes at the fetch line. I am testing with the pokemon API as it doesn’t require authentication and have also included it under permission in the manifest file.
Code:
import ForgeUI, { render, Fragment, Macro, Text, Heading, Button , useState} from "@forge/ui";
import {fetch} from '@forge/api';
const App = () => {
const [article, setArticle] = useState([]);
const numberOfURLs = 2;
const temp = [
{
id: 258,
name: "Mudkip"
},
{
id: 259,
name: "Marshtomp"
},
{
id: 260,
name: "Swampert"
}
]
const FetchDataFromAPI = async () => {
fetch("https://pokeapi.co/api/v2/pokemon/sawsbuck")
.then(async response => {
const data = await response.json();
if (!response.ok) {
const error = (data && data.message) || response.status;
// exit if failed
console.log(error);
return Promise.reject(error);
}
console.log("Promise returned")
const tempArticle = [{
id: "",
name: ""
}];
for (let i = 0; i < numberOfURLs; i++){
tempArticle[i] = {
id: dataReturn.forms[i].url,
name: dataReturn.forms[i].name,
};
}
setArticle(tempArticle);
})
.catch(error => {
console.error('There was an error!', error);
});
console.log("Reached end of function for method 1")
}
async function FetchDataFromAPI2 (){
const api = 'https://pokeapi.co/api/v2/pokemon/sawsbuck';
const result = await fetch(api);
const data = await result.json();
console.log("API CALLED SUCCESSFULLY");
const tempArticle = [{
id: "",
name: ""
}];
for (let i = 0; i < numberOfURLs; i++){
tempArticle[i] = {
id: data.forms[i].url,
name: data.forms[i].name,
};
}
setArticle(tempArticle);
console.log("Reached end of function for method 2")
}
const testDisplay = () =>{
setArticle(temp);
}
return (
<Fragment>
<Button
text ="Test output"
onClick={() => {
testDisplay();
}}/>
<Button
text ="Get data variant 1"
onClick={() => {
FetchDataFromAPI();
}}/>
<Button
text ="Get data variant 2"
onClick={() => {
FetchDataFromAPI2();
}}/>
{Array.from(article).map(article =>(
<Fragment key = {article.id}>
<Heading>This is pokemon number {article.id}!</Heading>
<Text>It's name is {article.name}</Text>
</Fragment>
))}
{Object.keys(article).length > 0
? <Text>There are items here</Text>
: <Text>No article retrieved yet. Click button to start.</Text>
}
</Fragment>
);
};
export const run = render(
<Macro
app={<App />}
/>
);
Manifest:
modules:
macro:
- key: test-api
function: main
title: test-api
description: Testing api calls!
function:
- key: main
handler: index.run
app:
id: ari:cloud:ecosystem::app/fc4c561b-52a2-4de8-a74c-8dde1100a84f
permissions:
external:
fetch:
backend:
- 'https://pokeapi.co/'
client:
- 'https://pokeapi.co/'
Output from forge tunnel:
2nd invocation is from the function FetchDataFromAPI2.
What is causing my code to not call the api/the promise does not return