skip to Main Content
import React, { useEffect, useState } from 'react';
import axios from "axios";
import './List.css';
import { toast } from "react-toastify";

const List = () => {
  const url = "http://localhost:4500";

  const [list, setList] = useState([]);

  const fetchList = async () => {
    const response = await axios.get(`${url}/api/food/list`);
    console.log("the response data", response.data);
    if (response.data.success) {
      
      setList(response.data.data)
    }
    else {
      toast.error("error")
    }
  }


  useEffect(() => {
    fetchList();
  }, []);

  useEffect(() => {
    console.log("the list type: ", typeof (list));
  }, [list]);

  return (
    <div className='list add flex-col'>
      <p>All food List</p>
      <div className="list-table">
        <div className="list-table-format title">
          <b>Image</b>
          <b>Name</b>
          <b>Category</b>
          <b>Price</b>
          <b>Action</b>
        </div>
        {list.map((item,index)=>{
          return(
            <div key={index} className="list-table-formate">
              <p>{item.name}</p>
            </div>
          )
        })}
      </div>
    </div>
  );
};

export default List;

,

In Above code when we insert the back-end api data in useState([]) empty array using fechList function so after inserted data list is empty.
if someone have Ans this problem so please discuss with me.
And also database api is respond the data properly.

I Axpecting that list is print in front-end and showing the data in front-end.

2

Answers


  1. From your code, it seems like you’re new to React and issues like these are handled in a certain manner. What improvements does it require?

    • A try-catch block or exception handling, so if the API is incase not returning anything or returning errors, you can log them in the console (console.log()) to get an idea.
    • A loader or loading indicator, so the return codes know when to return the views or visible elements, it will wait for the API fetching to be done and then return the elements or lists as received from API response.

    An updated, proper and scalable code will look something like this-

    import React, { useEffect, useState } from 'react';
    import axios from "axios";
    import './List.css';
    import { toast } from "react-toastify";
    import ClipLoader from "react-spinners/ClipLoader"; // Import a spinner loader to indicate users that it's loading
    
    const List = () => {
      const url = "http://localhost:4500";
    
      const [list, setList] = useState([]);
      const [isLoading, setIsLoading] = useState(true); // Add isLoading state to control the loader or loading
    
      const fetchList = async () => {
        // Use try catch finally block for API handling
        try {
          const response = await axios.get(`${url}/api/food/list`);
          console.log("the response data", response.data);
          if (response.data.success) {
            setList(response.data.data);
          } else {
            toast.error("Error fetching data");
          }
        } catch (error) {
          toast.error("Error fetching data");
        } finally {
          setIsLoading(false); // Set isLoading to false after data is fetched
        }
      };
    
      useEffect(() => {
        fetchList();
      }, []);
    
    
    
      return (
        <div className='list add flex-col'>
          <p>All Food List</p>
          {isLoading ? ( // Conditionally render the loader
            <div className="loader">
              <ClipLoader size={50} />
            </div>
          ) : (
            <div className="list-table">
              <div className="list-table-format title">
                <b>Image</b>
                <b>Name</b>
                <b>Category</b>
                <b>Price</b>
                <b>Action</b>
              </div>
              {list.map((item, index) => (
                <div key={index} className="list-table-format">
                  <p>{item.name}</p>
                </div>
              ))}
            </div>
          )}
        </div>
      );
    };
    
    export default List;
    

    If you still have any queries, leave a comment, I’ll help.

    Login or Signup to reply.
  2. The only thing that comes to my mind is that the response structure is different that the one that you expect here

    enter image description here

    try to check the response and see if it is ‘data.data’

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search