Reputation: 65
i'm a newbie in react and i have the following problem: i'm trying to get the objects from a get (axios) and play on the screen using the map, but i'm doing it wrong, if anyone can help me i would be grateful.
the requisition brought me the following items:
0: {username: "eqwe", name: "weqeqw", email: "eqwwqe", city: "qweewq", id: "fxm8j"}
1: {username: "sadsa", name: "asdads", email: "asdas", city: "sddsadsa", id: "79ywn"}
2: {username: "aaa", name: "aaa", email: "aaaa", city: "aaaaa", id: "8shpw"}
3: {username: "ddd", name: "ddd", email: "dddd", city: "ddd", id: "aourz"}
4: {username: "teste", name: "teste", email: "teste", address: {…}, city: "teste", …} ...
this is my code:
import {getUsers} from '../actions';
function Table(){
const [data, setData] = useState({data: []});
useEffect(() => {
async function fetchData(){
const result = await getUsers();
setData(result);
console.log("teste: ", result);
}
fetchData();
}, []);
return(
{data.map((item) =>
<div key={item.id}>{item.name}</div>)}
)
Upvotes: 0
Views: 67
Reputation: 103
You don't need to make nested object in state.
import {getUsers} from '../actions';
function Table(){
const [data, setData] = useState([]);
useEffect(() => {
async function fetchData(){
const result = await getUsers();
setData(result);
console.log("teste: ", result);
}
fetchData();
}, []);
return(
{data.map((item) =>
<div key={item.id}>{item.name}</div>)}
)
Upvotes: 1
Reputation: 130191
Just drop the { ... }
:
return data.map(item => (
<div key={item.id}>{item.name}</div>
));
{ }
inside a component are used to insert the result of an expression. However, you are not inside an element (not inside <tag> ... </tag>
) therefore { }
will just denote a block of code.
Upvotes: 0