Reputation: 41
I was able to retrieve JSON data via an API. However, I'm would like to know how I could retrieve my JSON data and display the output via a point form (example shown below). If anyone know how, please teach me. Much appreciate.
Code: Calling API
const [getText, setText] = useState("")
useEffect(() => {
const url = "API link"
const fetchData = async () => {
try{
const response = await fetch(url);
const json = await response.json();
console.log(json[0]["results");
getText(json.[0]["results"];
}catch (error) {
console.log("error", error)
}
};
fetchData();
}, []);
JSON File Format
"results": [
{
item_class_1: "class1"
item_value_1: "value1"
item_name_1: "name1"
}
{
item_class_2: "class2"
item_value_2: "value2"
item_name_2: "name2"
}
.
.
.
]
Expected Output in HTML:
class1: value1, name1
class2: value2, name2
Upvotes: 0
Views: 477
Reputation: 1392
Set the response data of API in the state by setText
as shown below:-
const [getText, setText] = useState([])
useEffect(() => {
const url = "API link"
const fetchData = async () => {
try{
const response = await fetch(url);
const json = await response.json();
console.log(json[0]["results");
setText(json.[0]["results"];
}catch (error) {
console.log("error", error)
}
};
fetchData();
}, []);
Now you can access the API response by calling getText and display the data as shown below:-
return (
<>
<h1>lakjdfkds</h1>
{this.state.data.map((item) => {
let values = Object.values(item)
return(
<>
{values[0]}: {values[1]}, {values[2]}<br/>
</>
)
})}
</>
)
Upvotes: 1