I want that if I click on the button for one of those users, a second Ajax call get triggered and shows only that user, which is clicked.
For this I tried the following:
import React, { useState, useEffect } from 'react'
function UserTile ({ setID, newID }) {
const [resources, setResources] = useState([])
const fetchResource = async (setID) => {
const response = await axios.get(
'https://api.randomuser.me/'
)
console.log(response.data.results)
setResources(response.data.results)
}
useEffect(() => {
fetchResource()
}, [])
resources.map((item) => {
if (item.login.uuid === newID) {
return (
<div className='card__item'>
<h2 className='card__title'>{item.name.first} {item.name.last}</h2>
<button className='btn--tile' onClick={() => setID(null)}>Back to overview</button>
Details
</div>
)
}
})
}
export default UserTile
But then if I click on the button of one of the users, instead of seeing only that user, I get the following error:
Uncaught Error: UserTile(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
What is wrong with my code?
I didn't understand what you tried to achieve by the question you asked. But by the looks for your code, it should be optimized and done the following way!
import React, { useState, useEffect, useCallback, memo } from "react";
import axios from "axios";
const UserTile = ({ setID, newID }) => {
const [resources, setResources] = useState([]);
const fetchResource = useCallback(async () => {
const response = await axios.get("https://api.randomuser.me/");
setResources(response.data.results);
}, []);
useEffect(() => {
fetchResource();
}, [fetchResource]);
const filteredResources = resources.filter(item => item.login.uuid === newID);
if (filteredResources.length === 0) {
return null;
}
return (
<div className="card__item">
<h2 className="card__title">
{filteredResources.name.first} {filteredResources.name.last}
</h2>
<button className="btn--tile" onClick={() => setID(null)}>
Back to overview
</button>
Details
</div>
);
};
export default memo(UserTile);
You should have at this point
resources.map((item) => {
if (item.login.uuid === newID) {
return (
<div className='card__item'>
<h2 className='card__title'>{item.name.first} {item.name.last}</h2>
<button className='btn--tile' onClick={() => setID(null)}>Back to overview</button>
Details
</div>
)
}
})
replaced with
return (<>
resources.map((item) => {
if (item.login.uuid === newID) {
return (
<div className='card__item'>
<h2 className='card__title'>{item.name.first} {item.name.last}</h2>
<button className='btn--tile' onClick={() => setID(null)}>Back to overview</button>
Details
</div>
)
}
})
</>)
and probably use filter instead of map
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.