0

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>)}
)
1
  • Can you please explain if you have any error message or where do you see any issues? What is the structure for result variable on the console? Commented Jan 18, 2020 at 16:04

2 Answers 2

1

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>)}
)
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.