Flask/React: Returned json data not being availabe

I would like to transfer quite a big amount of data (ca. 1 MB) to the client to plot it in the browser. When I use port 5000 (Flask) I see all the returned data but as soon as I switch to 3000 (React) I only get the message that the received data is 0 (=pretset data in useState). What am I doing wrong?

Python:

import pandas as pd
import time
import os
import json
import pandana
from pandana.loaders import osm
import warnings
import plotly
import plotly.express as px
import cartopy.crs as ccrs
from flask import Flask

app = Flask(__name__)

@app.route("https://stackoverflow.com/")
def map_nearest_pois():
    ... filling the (big) variable amenity_access ...

    fig = px.scatter(amenity_access, x='longitude', y='latitude', color="distance_next_amenity")
    graphJSON = plotly.io.to_json(fig, pretty=True)
    return graphJSON

if __name__ == "__main__":
   app.run(debug=True)

React:

import React, { useState, useEffect } from 'react'
import Plot from 'react-plotly.js'
import './App.css';

const App = () => {
  const [plot, setPlot] = useState(0);
  
  useEffect(() => {
    const fetchData = async () => {
      const data = await fetch("https://stackoverflow.com/")
        .then(res => res.json())
        .then(data => {setPlot(data);})
    }
    
    // call the function
    fetchData()
      .catch(console.error);
  }, [])


  return (
    <div className="App">
      <Plot data={plot.data} layout={plot.layout} />
    </div>
  );
}

export default App;

console.log shows me for “plot” just “0” and res.json() throws the then expected error that “0” is not json-formatted.
Where is the problem? Is it a time-dependent problem?

  • “console.log shows me for “plot” just “0” and res.json() throws the then expected error that “0” is not json-formatted.” – It’s not clear to me what you mean. Where in the code shown are you logging anything to the console? plot is initially set to 0, so it’s expected to be 0 at some point. And res.json() isn’t reading data from plot, so why would plot being 0 have any effect on that? Where is the port number used at all? What specifically is failing? In your browser’s debugging tools, when the AJAX request is made, what is the server’s response?

    – 

Leave a Comment