Home > Blockchain >  How to display data from Flask in React App?
How to display data from Flask in React App?

Time:12-26

I'm using Flask as a backend to retrieve data from MySQL database like that:

@app.route('/create', methods=['GET'])
def get_family():
    cursor.execute("SELECT * FROM individual")
    data = cursor.fetchall() 
    return render_template('index.html', data=data)

The last line sends the necessary data to the HTML file located in the templates folder and successfully displays my data in the table:

<table>
  <tr>
     <td>First Name</td>
     <td>Last Name</td>
     <td>Gender</td>
  </tr>
  {% for item in data %}
  <tr>
    {% for d in item %}
     <td>{{d}}</td>
     {% endfor%}
  </tr>
  {% endfor %}
 </table>

However, I want to display this data not in the html template but in my React application. I have a whole separate folder with my React files.

I added a proxy for my Flask API to avoid CORS issues, and allow React to handle the fetch calls and proxy them to right server. But now I am stuck with how to exactly display my data in React. Here is my initial attempt:

function Test() {
  const [myData, setMyData] = useState([{}])
  useEffect(() => {
    fetch('/create').then(
      response => response.json()
    ).then(data => setMyData(data.myData))
  }, []);
  return (
    <div>
      <table>
        <tr>
           <td>First Name</td>
           <td>Last Name</td>
           <td>Gender</td>
        </tr>
        mapping here?
        <tr>
          mapping here?
           <td>{{myData}}</td>
        </tr>
       </table>
    </div>
  );
}

I am unsure how exactly I should map in order to get my data displayed just like I did in that HTML template.

Any help would be appreciated!

CodePudding user response:

That's pretty simple and should be like this:

<table>
  <thead>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Gender</th>
    </tr>
  </thead>
  <tbody>
    myData.map((item, idx) => (
    <tr key={idx}>
      <td>{item.firstName}</td>
      <td>{item.lastName}</td>
      <td>{item.genre}</td>
    </tr>
  </tbody>
</table>

Or you could also map the td and have 2 map funcs.

CodePudding user response:

You can do it in a very similar way you did on your HTML template using .map

{myData.map((item) => (
  <tr>
    {item.map((d) => (
      <td>{d}</td>
    ))}
  </tr>
))}
  • Related