0

I have the wackiest bug. Like....the wackiest! If any of ya'll want to put eyes on this, awesomesauce! I really appriciate it! I am creating a survey with REACT, Redux, SQL, HML, Material-ui, and CSS.

I've created a graph of information with am4charts using data from a database. Everything is working and will show up on the page......but not on page load. What I am seeing in my console is that the page will load, it fires off my get request but doesn't return with the data fast enough (I think). By the time that the get request loads, my graph has populated with no data.

Here is the code that I have for the page that I am rendering. What is really odd is that, once my code has run, I can cut a line of code (I've been using a console log). And then the graph will render and load.

import * as am4core from "@amcharts/amcharts4/core";
import * as am4charts from "@amcharts/amcharts4/charts";

import React, { useRef, useState, useEffect } from 'react';
import axios from "axios";

function UnderstandingGraph(props) {
    
    const [feedback, setFeedback] = useState('');    

    // ⬇ Creating the chart
    const chart = useRef(null);
    
    useEffect(() => {
        // ⬇ This calls my get request from the server
        getFeedback();
        // ⬇ This creates the kind of chart that I would like from am4charts
        let x = am4core.create("chartdiv", am4charts.XYChart);
        // ⬇ Padding to the right of the graph
        x.paddingRight =  20;
        // ⬇ This declares what kind of date format I would like.
        x.dateFormatter.dateFormat = "yyyy-MM-dd";
        // ⬇ Adding from the data that I set in the getFeedback function
        let data = dataArray;
        // ⬇ Making the data tied to the chart, called x.
        x.data = data;
        // ⬇ creating xAxes (the horizontal axis)
        let dateAxis = x.xAxes.push(new am4charts.DateAxis());
        // dateAxis.title.text = "Date";
        dateAxis.renderer.grid.template.location = 0;
        // ⬇ creating yAxes (the vertical axis)
        let valueAxis = x.yAxes.push(new am4charts.ValueAxis());
        valueAxis.tooltip.disabled = true;
        valueAxis.renderer.minWidth = 35;
        // ⬇ Creating the series for a line graph
        let series = x.series.push(new am4charts.LineSeries());
        // ⬇ Binding the data to the series
        series.dataFields.dateX = "date";
        series.dataFields.valueY = "understanding";
        series.tooltipText = "{valueY.value}";
        x.cursor = new am4charts.XYCursor();
        // ⬇ Scrollbar functionality at the top of the graph
        let scrollbarX = new am4charts.XYChartScrollbar();
        scrollbarX.series.push(series);
        x.scrollbarX = scrollbarX;

        chart.current = x;
        
        return () => {
            x.dispose();
        };
    }, []);

    // ⬇ This gets my data from the database and sets it to feedback
    const getFeedback = ()  => {
        axios.get('/feedback') 
        .then( (response) => {
            setFeedback(response.data)
        })
        .catch((error) => {
            console.log(`We have a server error`, error);
        });
    }

    //!! Want the graph to render? Cut nearly any line from this page, then the graph will force reload and show. Why?
    //! I have been copy/pasting line 71 to make the graph show.
    //! Interesting though, that when the page loads, I only see one console.log. When I re-paste it, I see two...
    //! It's almost like the computer can't think fast enough to get the data and then come back. Is there an async screen pause?
    console.log('feedback', feedback)
    
    // ⬇ Arrays of the data I will need:
    const dataArray = []
    // ⬇ Loops through feedback 
    for (let i=0; i < feedback.length; i++){
        // ⬇ Checking that I can get the dates that I want - I can!
        // console.log(feedback[i])
        // console.log(feedback[i].date) // Will log the long long date
        // console.log(feedback[i].understanding) // Will log the number

        // ⬇ Makes an object, called data, that I can use to push into the dataArray.
        // Later we will use this to set the data points of the graph.
        let data = {
            "date": feedback[i].date,
            "understanding": feedback[i].understanding
        }
        dataArray.push(data)
    }

    

    return(
        <div id="chartdiv" style={{ width: "100%", height: "500px" }}></div>
    );
};

export default UnderstandingGraph;

What I have tried to fix this problem:

I have attempted to use two useEffects, like this:

useEffect(() => {
        // ⬇ This calls my get request from the server
        getFeedback();
}, [feedback]);

useEffect(() => {
        // ⬇ Code for the graph here
}, []);

But for some wacky reason that puts my server into an infinite loop. Then I tried:

useEffect(() => {
        // ⬇ This calls my get request from the server
        getFeedback();
}, []);

useEffect(() => {
        // ⬇ Code for the graph here
}, []);

And the graph will load, I will see my console logs on both the server side and in the browser...but no data populated in my graph :(

If anyone cares to see, this is what I have for my server get request to my database and also the sql data for the database.

//* GET REQUEST
// Will get all the responses
router.get('/', (req, res) => {
  let queryText = 'SELECT * from "feedback" ORDER BY "date" ASC;'
  pool.query(queryText).then( result => {
    // ⬇ Sends back the results in an object
      res.send(result.rows);
      console.log('Result from server:', result.rows)
  }).catch( error => {
      console.log('Error GET', error);
      res.sendStatus(500);
  });
});
CREATE TABLE "feedback" (
  "id" serial primary key,
  "feeling" INT not null,
  "understanding" INT not null,
  "support" INT not null,
  "comments" text,
  "flagged" boolean default false,
  "date" date not null default CURRENT_DATE
); 

-- Sample Data
INSERT INTO "feedback" ("feeling", "understanding", "support", "date")
VALUES 
(4, 4, 5, '2021-06-11'),
(4, 4, 5, '2021-06-10'),
(4, 2, 5, '2021-06-9'),
(2, 4, 5, '2021-06-7'),
(1, 3, 5, '2021-06-4'),
(4, 5, 5, '2021-06-2'),
(3, 3, 5, '2021-05-28'),
(3, 2, 5, '2021-05-26'),
(5, 4, 5, '2021-05-25'),
(2, 5, 5, '2021-05-24'),
(5, 5, 5, '2021-05-21');
MMettille
  • 19
  • 1
  • 5

1 Answers1

1

Can you try this fix? I created new functions for some tasks.

https://codesandbox.io/s/vigorous-varahamihira-6j588?file=/src/App.js