I am trying to follow the two examples at https://blog.logrocket.com/modern-api-data-fetching-methods-react/ described in sections "Using the JavaScript Fetch API" and "Using the async/await syntax".
I am attempting to apply both methods to https://dog.ceo/api/breeds/image/random inside a React app. I managed to get the second approach to work, but not the first. I am trying to understand better the difference between the two methods, particularly whether there is a fundamental issue with the first approach or whether I am simply not implementing it correctly.
I only have a vague understanding of asynchronicity and promises. I read through Async / await vs then which is the best for performance? but I don't feel like I have a good grasp on the issue yet. Perhaps someone could use the example below as an opportunity to help me understand the underlying concepts better?
"Then" Implementation
import {useEffect} from 'react';
export default function App() {
useEffect(() => {
fetch(`https://dog.ceo/api/breeds/image/random/`)
.then((response) => response.json())
.then((jsonResponse) => {
console.log(jsonResponse)
});
}, []);
return (
<div className="App">
</div>
);
}
Result in "Failed to fetch" error, see https://codesandbox.io/s/great-albattani-eu5zq1?file=/src/App.js
"Async/await" implementation"
import { useEffect } from "react";
export default function App() {
const getDogPic = async () => {
const response = await fetch("https://dog.ceo/api/breeds/image/random");
const dog = await response.json();
console.log(dog);
};
useEffect(() => {
getDogPic();
}, []);
return <div className="App"></div>;
}
Runs successfully, see https://codesandbox.io/s/keen-chaplygin-zr1pft?file=/src/App.js
CodePudding user response:
Remove the trailing slash from your first example
useEffect(() => {
fetch(`https://dog.ceo/api/breeds/image/random`)
.then((response) => response.json())
.then((jsonResponse) => {
console.log(jsonResponse)
});
}, []);
There's nothing special to understand here, that API endpoint just doesn't work with a trailing slash for whatever reason.