DEV Community

Cover image for UseState and UseEffect
Pranav Bakare
Pranav Bakare

Posted on • Edited on

UseState and UseEffect

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

Image description

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';

Enter fullscreen mode Exit fullscreen mode

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);
  }
};
Enter fullscreen mode Exit fullscreen mode

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>
);

Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)