Follow these steps to create a very simple fetch API example

  1. Use fake API data: https://jsonplaceholder.typicode.com/posts
  2. Create a new component in your React App
  3. Import useEffect, useState and axios
    NOTE: You may have to install axios if you don't already have it
    $ npm install --save axios
  4. Note1: To load only once onDidMount: useEffect(() => {}) If you see useEffect loads more then once,
    try this solution: https://www.webune.com/forums/ionic-typescript-react-application-useeffect-running-api-multiple-two-times-twice-duplicates.html
  5. Note2: To Re-render the variable everytime it changes use: ([varaiable1,variable2])

4. declare a posts useState:

const [posts, setPosts] = useState([]);

5. Add UseEffect():

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(res => {
        console.log(`LINE 11 res=`, res);
        setPosts(res.data)
      })
      .catch()
  })

6. Loop through the posts

      <ul>
        {posts.map(post => (
          <li key={post.id}>{post.title}</li>
        ))
        }
      </ul>

Complete Code:

import { useEffect, useState } from "react";
import axios from 'axios';

function Example() {
  const [posts, setPosts] = useState([]);
  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(res => {
        console.log(`LINE 11 res=`, res);
        setPosts(res.data)
      })
      .catch()
  })

  return (
    <ul>
      {posts.map(post => (
        <li key={post.id}>{post.title}</li>
      ))
      }
    </ul>
  )
}
export default Example;

 

0ZJgIjIuY7U