Reputation: 33
I'm a newbie in react and i'm trying to display the data i get from an array in my application. i make a get request with axios and the response shows me an array. i tried to follow a tutorial i found on internet in order to get this array displayed but it didn't work. could you check my code and tell me what is wrong with that? if my code is totally wrong could you advice me a way to get array displayed? thanks in advance
class Dashboard extends Component {
state = { data: [] };
static propTypes = {
history: PropTypes.object.isRequired,
}
constructor(props) {
super(props);
}
getAllLibri = async () => {
let JWTToken = localStorage.getItem("token");
const response = axios
.get("http://g0ptrkwkej5fhqfl.myfritz.net:8090/api/libri/getAll", {
headers: { Authorization: `${JWTToken}` },
})
.then((response) => {
console.log(response.data);
console.log(JWTToken);
this.setState({ data: response.data });
})
.catch((error) => console.error(`Error: ${error}`));
}
render() {
return (
<Navbar bg="light" expand="lg">
<Navbar.Brand href="#home">Benvenuto!</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="mr-auto">
<Nav.Link href="">Inserisci libro</Nav.Link>
<NavDropdown title="Libri" id="basic-nav-dropdown">
<NavDropdown.Item onClick={this.getAllLibri} href="#action/3.1">
Visualizza libri
<div>{this.state.data.length}</div>
</NavDropdown.Item>
</NavDropdown>
</Nav>
<Form inline>
<Button onClick={this.doLogout} variant="outline-success">
Logout
</Button>
</Form>
</Navbar.Collapse>
</Navbar>)
}
}
This is the array data i get from get request
Upvotes: 1
Views: 4489
Reputation: 905
When you get your data you have a plain array. You could use some array method like map:
{ data.map((item, index) => { return( <div key={index+1}>{item.value}</div> ) } ) }
This code generates as many <div>{item.value}</div>
as items in your array. map()
is an Array method that receives a function that is applied to every element in the array and returns the new elements in a new array, see this. The function in this case receives an item
and returns the item.value
in a div
element. As noticed in the comments, you also need to pass a key prop (starting with 1). React uses this value to identify the component and checks after a change if it has to re render it. I used the index
given as argument to the map callback but you could also use something like item.id
.
Upvotes: 1