im trying to render a list of objects, when i try map on console it returns the information correctly, i just need to render the object name in a list, but everytime i reload nothing renders on the screen, i don't know what i'm doing wrong.
import React from "react";
import { useState } from 'react'
import Swal from 'sweetalert2'
import AuthService from "../services/auth.service";
import { FcInfo } from 'react-icons/fc'
import { AiFillEdit } from 'react-icons/ai'
import { FiDelete } from 'react-icons/fi'
import { Card, InputGroup, FormControl, Button, DropdownButton, Dropdown,Table} from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import '../auth/login.css'
import solicitudeService from "../services/solicitude.service";
import edificeService from "../services/edifice.service";
import { render } from "@testing-library/react";
function MySolicitudes(){
var data=[]
solicitudeService.getAll().then(response =>{
data=response.data
data.map((val, key)=>{
console.log("TEST:",val.nombresolicitud,key);
});
console.log(data);
}).catch(e=>{
console.log(e);
});
return(
<div className="container">
<h3>Lista Espacios</h3>
<ul className="list-group">
{data && data.map((val,index) =>{
return( <li key={index}>
{val.nombresolicitud}
</li>);
})
}
</ul>
</div>
);
} export default MySolicitudes;
CodePudding user response:
The problem is that data
isn't part of the component's state, so reassigning it won't trigger a re-render.
Also, your code will currently call solicitudeService.getAll()
on every render, which you probably don't want.
Try using the useEffect
and useState
hooks:
const [data, setData] = useState([])
useEffect(() => {
solicitudeService.getAll().then(response =>{
setData(response.data);
console.log(data);
}).catch(e=>{
console.log(e);
});
}, []);
This will call solicitudeService.getAll()
once when the component is initially rendered, and then call setData
which should trigger a re-render and give you the behavior you expect.
You can adjust the deps array for useEffect
if you want to change when solicitudeService.getAll()
is called.
CodePudding user response:
data
is not a state variable here and as such does not excecute a rerender of your view (your load of the data via the solicitudeService is not synchronos and as such the data is not there when the page renders).
Put the data in a useState
hook and call the setter inside of youre solicitudeService.
Something like:
const [data, setData] = useState()
solicitudeService.getAll().then(response =>{
setData(response.data)
}).catch(e=>{
console.log(e);
});