How to fetch api in React.js?



    React.js Snippets

    First, the code initializes useState() to set up two variables: threads and setThreads. Then, it fetches the latest threads via the 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 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:

    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("").then(
          (response) =>
      useEffect(() => {
      }, []);
      return (
          {threads &&
   => (
              <div className="item-thread">
    class App extends React.Component {
      render() {
        return <Main />;
    ReactDOM.render(<App />, document.getElementById("container"));
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.