Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
React JS and flask functional component render on click

I am trying to create a simple app with flask and react to display some data using recharts.

This is what I have for the backend.

import random
import flask as flask
from flask import jsonify

app = flask.Flask(__name__)
@app.route('/api/chart_data')
def getChartData():
    data = list(map(lambda _: {'x': random.random()*100, 'y': random.random()*100}, range(20)))
    return jsonify(data)

And for the react front end I have:

import React,  { useState, useEffect } from 'react';
import { ScatterChart, Scatter, XAxis, YAxis, CartesianGrid } from 'recharts';

export default function RandomPlot()
{
    const [data, setData] = useState([]);
    useEffect(() => {
        fetch('/api/chart_data')
        .then((res) => res.json())
        .then((data) => {
            console.log("Plot data is: ", data);
            setData(data);
        });
    }, []);

    return (
        <>
            <div>
                <button>Generate new data</button>
                <ScatterChart width={400} height = {400}>
                    <CartesianGrid />
                    <XAxis type="number" dataKey="x" />
                    <YAxis type="number" dataKey="y" />
                    <Scatter data={data} fille="green" />
                </ScatterChart>
            </div>
        </>
    );
}

Desired result: I want the front end to display new data when the user presses the "generate new data" button.

What I have tried: I know that in the use effect hook you can pass in a values into the array so that the code runs every time one of the values changes. I tried adding an onClick function for the button that changes a variable that was passed into the use effect array. It didn't seem to work.

I am not sure what to pass into the useEffect array to get the desired result and how to write the onClick function.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I don't think you need the useEffect hook for this. useEffect runs whenever the data in the array at the second argument changes, or if the array is empty, it will run when the page first loads.

If you want to generate data whenever the user presses a button, then an onClick function should be enough. Let me know if it works! (By the way, this is my first time answering on StackOverflow so there maybe some formatting mistakes).

import React,  { useState, useEffect } from 'react';
import { ScatterChart, Scatter, XAxis, YAxis, CartesianGrid } from 'recharts';

export default function RandomPlot()
{
    const [data, setData] = useState([]);

    function genData(){
    fetch('/api/chart_data')
    .then((res) => res.json())
    .then((data) => {
        console.log("Plot data is: ", data);
        setData(data);
}

    return (
        <>
            <div>
                <button onClick={genData}>Generate new data</button>
                <ScatterChart width={400} height = {400}>
                    <CartesianGrid />
                    <XAxis type="number" dataKey="x" />
                    <YAxis type="number" dataKey="y" />
                    <Scatter data={data} fille="green" />
                </ScatterChart>
            </div>
        </>
    );
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda