I'm using a React hook component to fetch data from an api writed in express. It's only working while fetching all the data, trying to fetch any specific value, it crashes.
For example: It's fetching users.users
correctly but not users.users.details
react hooks component:
const Api = () => {
const [users, setUsers] = useState([{}]);
var {username} = useParams();
var objdetails = useRef();
function FetchApi(nameuser){
useEffect(() => {
fetch(`/api/users/${nameuser}/details`)
.then(res => res.json())
.then(users => setUsers({users}))
}, [nameuser])
}
FetchApi(username);
objdetails.current = JSON.stringify(users.users);
return(
<Styledthing>
<div>
<h2>User information from Github Api</h2>
<ul>
{JSON.stringify(objdetails.current)}
</ul>
</div>
</Styledthing>
);
}
export default Api;
api in express:
async pesquisarDetails (request,response){
let {username} = request.params
var details;
await axios.get('https://api.github.com/users/' + username).then(function(resposta){
details = resposta.data.login;
return response.json({details});
}).catch((err) => {
response.json({ msg:"User not found" + err + username });
})
}
Here's what happens in my browser(chrome) console:
api.js:25 Uncaught TypeError: Cannot read properties of undefined (reading 'details')
instead of:
objdetails.current = JSON.stringify(users.users.details);
try this:
objdetails.current = JSON.stringify(users.users?.details);
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.