First, the code initializes useState() to set up two variables: threads and setThreads. Then, it fetches the latest threads via the devHubby.com API. Finally, it sets the two variables to the response's data.
Next, useEffect() is invoked. This function takes two arguments: a function and an array of DOM nodes. The function is called once the effect has finished executing. In this case, getLatestPosts() is invoked, which fetches the latest posts from the devHubby.com API. The DOM nodes passed to useEffect() are then passed to the function as successive arguments.
Finally, the Main() component is rendered. This renders the <Main /> component, which contains the <div> nodes containing the threads data.
Discussion at: https://devhubby.com/thread/how-to-fetch-api-in-react-js
Library: react
Shortcut: api
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import axios from "axios";
const Main = () => {
const [threads, setThreads] = useState();
// Fetch Latest Threads via API
const getLatestPosts = async () => {
const response = await axios("https://devhubby.com/api/thread/latest").then(
(response) => response.data
);
setThreads(response.threads);
};
useEffect(() => {
getLatestPosts();
}, []);
return (
<div>
{threads &&
threads.map((thread) => (
<div className="item-thread">
<a
target="_blank"
rel="noreferrer"
href={`https://devhubby.com/thread/${thread.slug}`}
key={thread.id}
>
{thread.name}
</a>
</div>
))}
</div>
);
};
class App extends React.Component {
render() {
return <Main />;
}
}
ReactDOM.render(<App />, document.getElementById("container"));