Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React hooks not being set properly with JSON API response

I have tried setting my hooks to useState(null) useState([]) and useState() for initial page load, all with no success.

result.data and result.labels inside the fetch method all log to console with the appropriate data, but everytime I call setGraphData or setGraphLabels it just refuses to transfer the data to the hook variables

JSON Response:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Success true

labels [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", … ]

data [ {…}, {…}, {…}, {…} ]

0 Object { label: "", data: null, borderColor: "", … }

1 Object { label: "Kyle", borderColor: "#f6ff00", backgroundColor: "#f6ff00", … }

label "Kyle"

data [ "1517", "1689", "1719", "1591", "1490", "1310", "1533", "1500", "1400", "1300", … ]

borderColor "#f6ff00"

backgroundColor "#f6ff00"

2 Object { label: "Biprodeep", borderColor: "#ff0000", backgroundColor: "#ff0000", … }

3 Object { label: "Archisman", borderColor: "#001eff", backgroundColor: "#001eff", … }

import React from 'react';
import { Line } from 'react-chartjs-2';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js'
import { Chart } from 'react-chartjs-2'

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
)

function UploadFile() {

  const [graphData, setGraphData] = React.useState(null);
  const [graphDataFinal, setGraphDataFinal] = React.useState(null);
  const [graphLabels, setGraphLabels] = React.useState(null);
  const [isUploaded, setIsUploaded] = React.useState(false);
  var graphDataSets = [];

  function dropHandler(ev) {
    console.log('File(s) dropped');
  
    // Prevent default behavior (Prevent file from being opened)
    if (ev.dataTransfer.items) {
        // If dropped items aren't files, reject them
        if (ev.dataTransfer.items[0].kind === 'file') {
          var file = ev.dataTransfer.items[0].getAsFile();
          var data = new FormData()
          data.append('file', file)

          fetch('http://192.168.1.94:8081/upload', {
            method: 'post',
            body: data,
            headers: {
              'Authorization': localStorage.getItem('session-id')
            },
        }).then(response => response.json())
        .then(
          (result) => {
            DrawGraph(result.data, result.labels);
            setIsUploaded(true);
          },
          // Note: it's important to handle errors here
          // instead of a catch() block so that we don't swallow
          // exceptions from actual bugs in components.
          (error) => {
            console.log(error);
          }
        );
        }
    }
    ev.preventDefault();
    }

  function dragOverHandler(ev) {
    console.log('File(s) in drop zone');
  
    // Prevent default behavior (Prevent file from being opened)
    ev.preventDefault();
  }

  function DrawGraph(data, labels) {
    console.log("Draw Graph Executed")
    setGraphData(data);
    setGraphLabels(labels);
    for (var x in graphData) {
      if (x === 0) {
        
      } else {
        graphDataSets.push({ id: x, label: graphData[x].label, data: graphData[x].data, borderColor: graphData[x].borderColor, backgroundColor: graphData[x].backgroundColor })
      }
    }
    setGraphDataFinal(graphDataSets);
    console.log(graphDataFinal);
  }

  return (
    <div>
      <div id="drop_zone" onDrop={dropHandler} onDragOver={dragOverHandler}>
        <p className="drop_zone">Drag one or more files to upload and generate a graph</p>
      </div>
      <br></br>
        {isUploaded ? <div className="graph-area"><Line
          datasetIdKey='myLine'
          data={{
            labels: graphLabels,
            datasets: graphDataFinal,
          }}
        /></div> : null}
    </div>
    )
}

export default UploadFile

>Solution :

React does not immediately updates state so in function draw graph use data variable in for loop instead of graphData and update code as well which you want immediate effect/change in state.

function DrawGraph(data, labels) {
console.log("Draw Graph Executed")
setGraphData(data);
setGraphLabels(labels);
for (var x in data) {
  if (x === 0) {
    
  } else {
    graphDataSets.push({ id: x, label: graphData[x].label, data: graphData[x].data, borderColor: graphData[x].borderColor, backgroundColor: graphData[x].backgroundColor })
  }
}
setGraphDataFinal(graphDataSets);
console.log(graphDataSets);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading