I want to create a chart on the backend and send it to the frontend to display it.
My endpoint /chart/ return plot this way:
from dataclasses import dataclass
import plotly.graph_objects as go
import plotly.io as pio
@dataclass
class DataChart:
category: list[str]
points: list[int]
class GenerateChart:
def __init__(self, data: DataChart):
assert isinstance(data, DataChart)
self.category = data.category
self.points = data.points
def generate_chart(self):
fig = go.Figure()
fig.add_trace(
go.Scatterpolar(
r=self.points,
theta=self.category,
fill="toself",
name="A",
)
)
fig.update_layout(
polar={"radialaxis": {"visible": True, "range": [0, 10]}}, showlegend=False
)
html_str = pio.to_html(fig, include_plotlyjs="cdn", full_html=False)
return html_str
and frontend:
const generateChart = async (queue_smooth_data: {}) => {
const response = await fetch("http://127.0.0.1:8000/chart/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(queue_smooth_data),
});
response.text().then((text) => {
setChartHTML(text);
});
if (currentQuestionIndex > dataQuiz.length) {
return (
<div>
<div dangerouslySetInnerHTML={{ __html: chartHTML }}></div>
</div>
);
}
but it returns in html this:
"
\n
"
Does anyone know where I made a mistake? My raw html data looks like this:
"<div> <div id=\"1d254924-7635-493b-87bb-e44ced485435\" class=\"plotly-graph-div\" style=\"height:100%; width:100%;\"></div> <script type=\"text/javascript\"> window.PLOTLYENV=window.PLOTLYENV || {}; if (document.getElementById ...
Additional question - is this a good way to upload charts? From what I've figured out usually you save the chart to a file and read it from there, but I want to just display the chart without unnecessarily saving it.
I tried different ways to send data - setting include_plotlyjs="cdn", True, False, also imported into HTML plotly:
<script
src="https://cdn.plot.ly/plotly-2.20.0.min.js"
charset="utf-8"
></script>
also installing plotlyjs npm