I am using NextJS to display data obtained from a DB in a table, once I fetch the data I want to use the map
function to create the table row and then insert it on the table
import React, {useEffect, useState} from 'react'
import { Container, Table } from 'react-bootstrap'
import axios from 'axios'
export default function index() {
const [object, setObject] = useState({
type: '',
date: '',
user: 0
})
const fetchData = async () =>{
const results = await axios.get(`my api url`)
setObject(results.data.result)
}
useEffect(() =>{
fetchData()
},[])
if(object.user != 0){
const objectRow = object.map(
(index: any) =>{
return(
<tr>
<td>{index.type}</td>
<td>{index.date}</td>
<td>{index.user}</td>
</tr>
)
}
)*/
}
return (
<Container>
<Table bordered hover >
<thead>
<tr>
<th>Type</th>
<th>Date</th>
<th>User/th>
</tr>
</thead>
<tbody>
{objectRow}
</tbody>
</Table>
</Container>
)
}
I’m getting an error Property 'map' does not exist on type
followed by the properties of object
.
Is my approach worng? How can I map the data?
2
Answers
object
isn’t an array. Useto make it an array.
And make sure that the result of the API call is an array.
Hello
You’r provided code have some errors i am providing a possible better version of your code
}