1

I am creating a react web app and I am going to be displaying data using googles charts for react. I have a function displayDataChart() that returns a pie chart with dummy data to test. However, when I boot up the website on local host, the graph isnt there. It is just an empty section tag. The code is below.

//DASHBOARD PAGE FILE
import {useEffect} from 'react'
import {useNavigate} from 'react-router-dom'
import {useSelector, useDispatch} from 'react-redux'
import Spinner from '../components/Spinner'
import { getExpenses, reset } from '../features/expenses/expenseSlice'
import ExpenseItem from '../components/ExpenseItem'
import TotalItem from '../components/TotalItem'
import {useState} from 'react'
import {Chart} from 'react-google-charts'

function Dashboard() {
  const navigate = useNavigate()
  const dispatch = useDispatch()
  const {user} = useSelector((state) => state.auth)
  const {expenses, isLoading, isError, message} = useSelector((state) => state.expenses)
  const [dateRange, setDateRange] = useState(getDate('weekly'))
  const [category, setCategory] = useState('all')
  const d1 = new Date()
  const today = d1.toLocaleDateString()
  const [sortType, setSortType] = useState('none')

  const sortMethods = {
    none: { method: (a, b) => null },
    amountAscending: { method: (a, b) => ((parseFloat(a.amount) > parseFloat(b.amount)) ? 1 : -1)  },
    amountDescending: { method: (a, b) => ((parseFloat(a.amount) < parseFloat(b.amount)) ? 1 :-1) },
    dateAscending: { method: (a, b) => ((a.date > b.date) ? 1 : -1)  },
    dateDescending: { method: (a, b) => ((a.date < b.date) ? 1 :-1) }
  }
  
  useEffect(() => {
    if(isError){
      console.log(message);
    }

    if(!user){
      navigate('/login')
    }
    else(

      dispatch(getExpenses([dateRange[0], dateRange[1] ,category]))
    )

    return () => {
      dispatch(reset())
    }
   
    }, [user, navigate, isError, message, dispatch]
  )

  if(isLoading){
    return <Spinner />
  }

  function displayDataChart(){
    return <section className='content'>
      <Chart
        chartType="PieChart"
        data={[
          ["Task", "Hours per Day"],
          ["Work", 11],
          ["Eat", 2],
          ["Commute", 2],
          ["Watch TV", 2],
          ["Sleep", 7]
        ]}
        options={{
          title: "My Daily Activities",
        }}
        width={"100px"}
        height={"100px"}
      />
    </section>
  }
  
  function displayTotal(totalVal){
    if(expenses.length > 0){
      return <section className='content'>
      <TotalItem total={totalVal}/>
      </section>
    }
  }

  function getTotal(){
    let total = 0
    {expenses.map((expense) =>(
      total += parseFloat(expense.amount)
    ))}
    return total
  }

  function displaysExpenses(){
    return <section className="content">
    {expenses.length > 0 ? (
      <div className="expenses">
        {expenses.map((expense) =>(
          <ExpenseItem key={expense._id} expense ={expense}/>
        ))}
      </div>
    ) : (<h3>No expenses have been added</h3>)}
  </section>
  }

  const getDaysInMonth = (year, month) => new Date(year, month, 0).getDate()

  const addMonths = (input, months) => {
    const date = new Date(input)
    date.setDate(1)
    date.setMonth(date.getMonth() + months)
    date.setDate(Math.min(input.getDate(), getDaysInMonth(date.getFullYear(), date.getMonth()+1)))
    const res = new Date(date.getFullYear(), date.getMonth(), 1)
    return res.toLocaleDateString()
  }

  function formatDate(date){
    const split = date.split('/')
    let year = split[2].toString()
    let month = split[0].toString()
    let day = split[1].toString()

    if (split[0].length < 2){
      month = '0' + month
    }

    if (split[1].length < 2){
      day = '0' + day
    }

    return year + '-' + month + '-' + day
  }
  
  function getToday() {
    const today = new Date()
    const tomorrow = new Date(today)
    tomorrow.setDate(tomorrow.getDate() + 1)
    return[formatDate(today.toLocaleDateString()), formatDate(tomorrow.toLocaleDateString())]
  }
  
  function getMonday(d){
    const dt = new Date(d)
    const day = dt.getDay()
    const diff = dt.getDate() - day + (day === 0 ? -6 : 1);
    return new Date(dt.setDate(diff)).toLocaleDateString()
  }

  function getSunday(d){
    var date = new Date(d);
    if (date.getDay() === 0) {
        return date.toLocaleDateString()
    }
    else{
        date.setDate(date.getDate() + (0 - 1 - date.getDay() + 7) % 7 + 1);
        return date.toLocaleDateString()
    }
}

function getWeekly(d) {
  return [formatDate(getMonday(d)), formatDate(getSunday(d))]
}

function getMonthly(d) {
  const date = new Date(d);
  var firstDay = new Date(date.getFullYear(), date.getMonth(), 1)
  var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0)
  return [formatDate(firstDay.toLocaleDateString()), formatDate(lastDay.toLocaleDateString())]
}

function getPast6Months(d){
  return [formatDate(addMonths(d, -6)), formatDate(d.toLocaleDateString())]
}

function getYearly(d){
  return [formatDate(addMonths(d, -12)), formatDate(d.toLocaleDateString())]
}

 function getDate(type){
    const todaysDate = new Date()
    let returnDate = new Date()

    switch(type){
      case "today":
        return getToday()
      case "weekly":
        return getWeekly(todaysDate)
      case "monthly":
        return getMonthly(todaysDate)
      case "6 months":
        return getPast6Months(todaysDate)
      case "yearly":
        return getYearly(todaysDate)
      case "all time":
        return "2000-01-01"
    }
  }


  return(
    <>
    <section className='heading'>
      <h1>{user && user.firstName + " " + user.lastName}'s Dashboard </h1>
    </section>

    <section className='form'>
      <div className='form-group'>
        <label htmlFor='dateRange'>See Expenses From</label>
        <select type='text' name='dateRange' id='dateRange' value={dateRange} onChange={(e) => {setDateRange(e.target.value); dispatch(getExpenses([e.target.value.split(',')[0], e.target.value.split(',')[1], category]))}} >
          <option value={getDate("weekly")}>This Week</option>
          <option value={getDate("today")}>Today</option>
          <option value={getDate("monthly")}>This Month</option>
          <option value={getDate("6 months")}>Past 6 months</option>
          <option value={getDate("yearly")}>This year</option>
          <option value={getDate("all time")}>All Time</option>
        </select>
        
        <label htmlFor='category'>Filter By Category</label>
        <select type='text' name='category' id='category' value={category} onChange={(e) => {setCategory(e.target.value); dispatch(getExpenses([dateRange.split(',')[0], dateRange.split(',')[1], e.target.value]))}} >
            <option value="all">All</option>
            <option value="Food">Food</option>
            <option value="Rent">Rent</option>
            <option value="Utilities">Utilities</option>
            <option value="Subcription">Subscription</option>
            <option value="Payment to another entity">Payment to another entity</option>
            <option value="Other">Other</option>
          </select>

        <label htmlFor='sortType'>Sort By</label>
        <select type='text' name='sortType' id='sortType' value={sortType} onChange={(e) => {setSortType(e.target.value)}} >
            <option value="none">None</option>
            <option value="dateDescending">Date: Newest to Oldest</option>
            <option value="dateAscending">Date: Oldest to Newest</option>
            <option value="amountDescending">Amount: High to Low</option>
            <option value="amountAscending">Amount: Low to High</option>
          
          </select>
      </div>

    </section>

    {displayTotal(getTotal())}
    {displaysExpenses()}
    {displayDataChart()}

 
    </>
)
}

export default Dashboard

In the image attached you can see that the graph is not displaying and in the inspect elements tab, the last section tag (with className as content) is empty. I cant get the graph to render at all.

Screenshot

Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41
billycodes
  • 11
  • 2

0 Answers0