Remove the typo in your url '
I've added loading
and error
state as well because I think that it is a very common practice to handle loading
and error
state. I've also make your contents into an array and render your array using map
Note that I've used dangerouslySetInnerHTML
props and it is known to be very dangerous and risky to a cross-site scripting (XSS) attack.
import ReactDOM from "react-dom";
import React, { useState, useEffect } from "react";
const App = () => {
const [contents, setContents] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState();
const url =
"https://en.wikipedia.org/w/api.php?action=query&origin=*&prop=extracts&format=json&exintro=&titles=Berlin";
const extractAPIContents = (json) => {
const { pages } = json.query;
return Object.keys(pages).map(id => pages[id].extract);
}
const getContents = async () => {
let resp;
let contents = [];
setLoading(true);
try {
resp = await fetch(url);
const json = await resp.json();
contents = extractAPIContents(json);
} catch(err) {
setError(err);
} finally {
setLoading(false);
}
setContents(contents);
};
useEffect(() => {
getContents();
}, []);
if (loading) return 'Loading ...';
if (error) return 'An error occurred';
return (
<div>
<h1>Article</h1>
{contents.map(content => <div dangerouslySetInnerHTML={{ __html: content }} />)}
</div>
)
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Here is a working demo : https://codesandbox.io/s/blissful-davinci-m5j9i?fontsize=14&hidenavigation=1&theme=dark