This content originally appeared on DEV Community and was authored by Pranav Bakare
Your HomeScreen component is set up to fetch product data from an API endpoint and store it in state using React hooks. To make it fully functional, you'll need to ensure a few things:
UseState and UseEffect
1. Import Statements: Ensure that you import useState, useEffect, and axios at the top of your file:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
2. Error Handling: Consider adding error handling for the API call to manage any issues with data fetching:
const fetchProducts = async () => {
try {
const { data } = await axios.get('/api/products');
setProducts(data);
} catch (error) {
console.error('Error fetching products:', error);
}
};
3. Rendering: Add rendering logic to display the fetched products:
return (
<div>
<h1>Product List</h1>
{products.length > 0 ? (
<ul>
{products.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
) : (
<p>Loading products...</p>
)}
</div>
);
Here's the complete updated code:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const HomeScreen = () => {
const [products, setProducts] = useState([]);
useEffect(() => {
const fetchProducts = async () => {
try {
const { data } = await axios.get('/api/products');
setProducts(data);
} catch (error) {
console.error('Error fetching products:', error);
}
};
fetchProducts();
}, []);
return (
<div>
<h1>Product List</h1>
{products.length > 0 ? (
<ul>
{products.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
) : (
<p>Loading products...</p>
)}
</div>
);
};
export default HomeScreen;
This will ensure that your component fetches and displays the list of products correctly while handling potential errors.
This content originally appeared on DEV Community and was authored by Pranav Bakare
Pranav Bakare | Sciencx (2024-09-19T15:33:35+00:00) UseState and UseEffect. Retrieved from https://www.scien.cx/2024/09/19/usestate-and-useeffect/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.