beginner webdev here
i'm trying to display the relevant random user data as such in my react component into the below html table by acccessing the properties of the user object, however im not sure how to access them outside of the async function. I'm not even sure if i should be using async here haha. How if at all would i be able to do this?? i even tried making a whole new object insantiator but it wouldn't work.
Thanks!!
import React, { useState, useEffect } from "react";
const UserTable = () => {
const API_URl = "https://randomuser.me/api/";
async function LoadTable() {
const response = await fetch(API_URl);
const data = await response.json();
const person = data.results;
console.log(person);
return LoadTable;
}
LoadTable();
return (
<table>
<tr>
<th>name</th>
<th>age</th>
<th>gender</th>
</tr>
</table>
);
};
export default UserTable;
CodePudding user response:
- Do not call
LoadTable
in render. Call it in an event handler oruseEffect
. - Store the result in state.
- Wrap your async functions or functions that may throw an error in a
try catch finally
block. - You can store loading state in component state.
- You can store error in state.
- Make sure you handle different scenarios and race conditions that may occur.
CodePudding user response:
import React, { useState, useEffect } from "react";
const UserTable = () => {
const API_URl = "https://randomuser.me/api/";
// declare state
const [person, setPerson] = useState(null);
// call `LoadTable` inside `useEffect` for safety
useEffect(() => {
async function LoadTable() {
const response = await fetch(API_URl);
const data = await response.json();
const person = data.results;
// setState
setState(person);
}
LoadTable();
}, [])
// do something with `person` down here
return (
<table>
<tr>
<th>name</th>
<th>age</th>
<th>gender</th>
</tr>
</table>
);
};
export default UserTable;