UseState and UseEffect
Pranav Bakare
Posted on September 19, 2024
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.
Reference
import { useState, useEffect } from 'react';
import { Row, Col } from 'react-bootstrap';
import Product from '../components/Product';
//import products from '../products';
import axios from 'axios';
const HomeScreen = () => {
const [products, setProducts] = useState([]);
useEffect(() => {
const fetchProducts = async () => {
const { data } = await axios.get('/api/products');
setProducts(data);
};
fetchProducts();
}, []);
return (
<>
<h1>Latest Products</h1>
<Row>
{products.map((product) => (
<Col key={product._id} sm={12} md={6} lg={4} xl={3}>
<Product product={product} />
</Col>
))}
</Row>
</>
);
};
export default HomeScreen;
Posted on September 19, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.