skip to Main Content

I have a component that fetches data from an API (nodeJS server). All my fetch code is an useEffect hook. But on running the code the useEffect code does not run as i am unable to see my console.log statements and my state is not set.

Is there anything wrong with my code, as I have referred articles online and tried many approaches
How do I set my state variable once the useEffect is run and any help is understanding useEffect would be helpful.


export default function SummaryContainer() {
  /* const { transactions, setTransactions } = useTransactionContext(); */
  let apiData = null;
  const [summary, setSummary] = useState([]);
  useEffect(() => {
    const url = "http://localhost:3000/getExpenseSummary";

    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const data = await response.json();
        console.log(data);
        console.log("Fetched Data");
        setSummary(data);
      } catch (error) {
        console.log("error", error);
      }
    };

    fetchData();
  }, []);

  /* const expenseSummary = calculateExpenses(transactions) ?? null; */

  return (
    <div>
      {summary.map((expense, idx) => {
        const formattedString =
          expense[0].slice(0, 1).toUpperCase() + expense[0].slice(1);
        return (
          <Summary
            key={idx}
            title={formattedString}
            value={expense[1]}
            desc={"Total " + formattedString}
          />
        );
      })}
    </div>
  );
}


2

Answers


  1. export default function SummaryContainer() {
     /* const { transactions, setTransactions } = useTransactionContext(); */
     let apiData = null;
     const [summary, setSummary] = useState([]);
     const url = "http://localhost:3000/getExpenseSummary";
    
    const fetchData = async () => {
       try {
            const response = await fetch(url);
            const data = await response.json();
            console.log(data);
            console.log("Fetched Data");
            setSummary(data);
        } catch (error) {
            console.log("error", error);
        }
    };
    
    useEffect(() => {
        fetchData();
    }, []);
    
    /* const expenseSummary = calculateExpenses(transactions) ?? null; */
    
    return (
        <div>
            {summary.map((expense, idx) => {
                const formattedString =
                    expense[0].slice(0, 1).toUpperCase() + expense[0].slice(1);
                return (
                    <Summary
                        key={idx}
                        title={formattedString}
                        value={expense[1]}
                        desc={"Total " + formattedString}
                    />
                );
             })}
         </div>
      );
    }
    

    Can you execute the above code I have made the changes.

    Login or Signup to reply.
  2. Your code is correct. There might be issue with expense[0] that is used in the formatted string. Since we do not have what the response is from the backend, I cannot say if the expense field is an array or not. Here I have added my changes, with the condition that the expense field might be a key-value pair.

    You can also make the value capital using the css property capitalize.

    CodeSandbox

    Text Transform – Capitalize

    Do note that I have made the first 3 letters capital, since the response already has the first letter in capital.

    import { useState, useEffect } from "react";
    
    export default function App() {
      const [summary, setSummary] = useState([]);
      useEffect(() => {
        const url = "https://jsonplaceholder.typicode.com/users";
    
        const fetchData = async () => {
          try {
            const response = await fetch(url);
            const data = await response.json();
            console.log(data);
            console.log("Fetched Data");
            setSummary(data);
          } catch (error) {
            console.log("error", error);
          }
        };
    
        fetchData();
      }, []);
    
      /* const expenseSummary = calculateExpenses(transactions) ?? null; */
    
      return (
        <div>
          {summary.length > 0 ? (
            summary.map((expense, idx) => {
              const formattedString =
                expense.name.slice(0, 3).toUpperCase() + expense.name.slice(1);
              return (
                <>
                  <b>{formattedString}</b> <br />{" "}
                </>
              );
            })
          ) : (
            <p>Fetching data...</p>
          )}
        </div>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search