'How show display all data using fetch method in React.js
I am Beginning in Programming. Now am trying to show All data in the display using the fetch data method. But Couldn't show this.
import { useEffect, useState } from "react";
const useProducts = () => {
const [items, setItems] = useState([]);
useEffect(() => {
fetch("https://damp-island-69804.herokuapp.com/inventory")
.then(res => res.json)
.then(data => setItems(data))
}, [])
return [items, setItems];
}
export default useProducts;
What's the problem with this code? Please Help.
Solution 1:[1]
please note res => res.json in your code should be res.json() as it is a function not property.
Solution 2:[2]
Refer This example : https://www.freecodecamp.org/news/fetch-data-react/
- Use resp.json() instead of resp.json
- Check resp.ok if not throw exception. Then set the exception message in another state variable.
- If loader used, show and hide accordingly by using the setter.
- Add try and catch accordingly And do clean up in the finally block.
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 | Daljit Kumar |
| Solution 2 | Senthil |
