I have an array of users, and every user has its data.
I'm trying to extract user number 1 (id=1) and then save it in useState
. After that, I want to map it and print it as li.
so far I've had no success.
import logo from './logo.svg';
import './App.css';
import './myCss.css';
import { useState ,useEffect } from 'react';
import axios from 'axios'
import Page2 from './Page2'
function Page3() {
const [users,setusers] = useState([])
const [user,setUser] = useState({})
useEffect(() => {
async function fetchData() {
let resp = await axios.get("https://jsonplaceholder.typicode.com/users");
setusers(resp.data);
}
fetchData();
}, []);
// In this function I try to print the information
const getData = () =>
{
let myUser2 = users.filter(x=>x.id==1)
setUser(myUser2)
{
user.map((item,index)=>
{
return <li key = {index}>{item}</li>
})
}
}
return (
<div className = "styles">
<input type = "button" value = "Get Data for comp 1" onClick = {getData}/>
</div>
);
}
export default Page3;
CodePudding user response:
First I have a question why would you want to map through a state that contains only one value. I see no point in this, however in case you will store more information inside userstate you may try something like the following:
const getData = () => {
let myUser2 = users.filter(x=>x.id==1)
setUser(myUser2)
}
const printUser = user.map((item, index) => <li key={item index}>{item}</li>
return (
<div className = "styles">
<input type = "button" value = "Get Data for comp 1" onClick = {getData}/>
<ul>
{printUser && printUser}
</ul>
</div>
);
}
export default Page3;
CodePudding user response:
You cannot print data in getData
which is an event function. Instead of that, you should add it to JSX.
Besides that, user
is a single user and users
are a list of users. filter
is not fit for your case in finding a single user, I'd suggest that you use find
instead. find
will return an object, so you don't need to use map
for renderings.
//`user` is an empty object, so we need to make sure it has data inside `user` with `Object.keys`
{user && Object.keys(user) > 0 && <li key={user.name}>{user.name}</li>)}
Full possible modification
function Page3() {
const [users,setusers] = useState([])
const [user,setUser] = useState({})
useEffect(() => {
async function fetchData() {
let resp = await axios.get("https://jsonplaceholder.typicode.com/users");
setusers(resp.data);
}
fetchData();
}, []);
const getData = () =>
{
let myUser2 = users.find(x=>x.id==1)
setUser(myUser2)
}
return (
<div className = "styles">
<input type = "button" value = "Get Data for comp 1" onClick = {getData}/>
<ul>
{user && Object.keys(user) > 0 && <li key={user.name}>{user.name}</li>)}
</ul>
</div>
);
}
export default Page3;