Estoy usando Flask como backend para recuperar datos de la base de datos MySQL así:
@app.route('/create', methods=['GET']) def get_family(): cursor.execute("SELECT * FROM individual") data = cursor.fetchall() return render_template('index.html', data=data)La última línea envía los datos necesarios al archivo HTML ubicado en la carpeta de plantillas y muestra correctamente mis datos en la tabla:
<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>Sin embargo, quiero mostrar estos datos no en la plantilla html sino en mi aplicación React. Tengo una carpeta completamente separada con mis archivos React.
Agregué un proxy para mi Flask API para evitar problemas de CORS y permitir que React maneje las llamadas de búsqueda y las envíe al servidor correcto. Pero ahora estoy atascado con la forma exacta de mostrar mis datos en React. Aquí está mi intento inicial:
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> ); }No estoy seguro de cómo debo mapear exactamente para que mis datos se muestren tal como lo hice en esa plantilla HTML.
¡Cualquier ayuda sería apreciada!
Puede hacerlo de una manera muy similar a como lo hizo en su plantilla HTML usando .map
{myData.map((item) => ( <tr> {item.map((d) => ( <td>{d}</td> ))} </tr> ))}Eso es bastante simple y debería ser así:
<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>O también podría mapear el td y tener 2 funciones de mapa.