首页 > 其他分享 >How To Fetch API Data With React

How To Fetch API Data With React

时间:2023-07-07 10:23:53浏览次数:38  
标签:const users App React How API data

Fetching data from third-party RESTful APIs in React application is a common task when creating web application. This task can be solved easily by using the standard JavaScript Fetch API in your React application.

The Fetch API is a new standard to make server requests with Promises, but which also includes additional features. This short tutorial will guide you through the simple steps of using the Fetch API for external data fetching within your React application. Let’s get started …

Step 1: Create a new React application

The very fist step is to create a new React application. The easiest way to do so, is to use the create-react-app scaffolding script which can be executed with the following command:

$ npx create-react-app fetch-app

This command is creating a new default React project in folder fetch-app.

Creating a new React application with create-react-app

Step 2: Select a data source

Next we need an external data source which we can use to retrieve data from. I service which is free to use and is offering multiple endpoints which JSON formatted test data is JSONPlaceholder which is available at https://jsonplaceholder.typicode.com/:

JSONPlaceholder is available at https://jsonplaceholder.typicode.com/

Here we’ll be using the users endpoint to retrieve user sample data for our React application:

Users endpoint of JSONPlaceholder available at https://jsonplaceholder.typicode.com/users

Step 3: Use Fetch API to retrieve data

Let’s return to the newly created React project and add the JavaScript code which is needed to retrieve data from the JSONPlaceholder REST endpoint.

Open file src/App.js and change the default App component implementation to the following:

const App = () => {
  return (
    <div>
      Test
    </div>
  );
}

export default App;

Next add the following import statement on top:

import React, { useEffect, useState } from “react”

By using this import statement we’re making sure that we’re able to make use of React’s useEffect and useState hook.

Inside App function introduce a new users component state which will later on hold our retrieved user sample data by using the useState hook:

const [users, setUsers] = useState([])

Next add a function fetchUserData which uses the Fetch API to retrieve data from the users endpoint of the JSONPlaceholder service:

import React, { useEffect, useState } from "react"

const App = () => {
  const [users, setUsers] = useState([])

  const fetchUserData = () => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(response => {
        return response.json()
      })
      .then(data => {
        setUsers(data)
      })
  }
  
  return (
    <div>
      Test
    </div>
  );
}

export default App;

If the data is retrieved successfully we’re calling setUsers function in order to set the component user state to the data which was retrieved.

Step 4: Make sure data fetching is executed everytime your React app loads

Next we need to make sure that fetchUserData is executed. We want it to be executed everytime App component loads. This can be achieved by using the useEffect hook in the following way:

useEffect(() => {
  fetchUserData()
}, [])

Step 6: Output fetched data

Finally we need to show the retrieved data to the user. Change the return statement of App component to what you can see in the following code listing:

import React, { useEffect, useState } from "react"

const App = () => {
  const [users, setUsers] = useState([])

  const fetchUserData = () => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(response => {
        return response.json()
      })
      .then(data => {
        setUsers(data)
      })
  }

  useEffect(() => {
    fetchUserData()
  }, [])

  return (
    <div>
      {users.length > 0 && (
        <ul>
          {users.map(user => (
            <li key={user.id}>{user.name}</li>
          ))}
        </ul>
      )}
    </div>
  );
}

export default App;

This code iterates to the data which is stored in users state and outputs the name of each user as a list item.

Start the React development web server by typing in

$ npm start

on the command line and you should be able to see the following result in the browser:

Result

Done, that’s it! 6 easy steps and the goal is achieved: user sample data has been retrieved from a third-party service in your React application by using JavaScript’s Fetch API and outputted in the browser. That’s how easy it is to retrieve API data with React

标签:const,users,App,React,How,API,data
From: https://www.cnblogs.com/weifeng1463/p/17534103.html

相关文章

  • ctfshow刷题(Java反序列化)
    CTFshowJava反序列化web846urldns链importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.ObjectOutput;importjava.io.ObjectOutputStream;importjava.lang.reflect.Field;importjava.net.URL;importjava.util.Base64;i......
  • API接口的重要性
    API接口的重要性在现代软件开发中无可替代。以下是API接口的几个重要方面:1.实现系统集成:API接口允许不同应用程序之间实现数据共享和交流。通过API接口,不同的软件系统可以相互连接和协作,实现系统集成。这样可以提高系统的功能和效率,让不同系统之间实现无缝衔接。2.增加开发效......
  • 想了解API接口,这一篇就够了
    API(ApplicationProgrammingInterface)接口,对于大多数人来说可能还比较陌生,但实际上我们每天都在与它打交道。无论是使用手机上的应用程序,还是在网上购物,都少不了API接口的应用。那么,到底什么是API接口呢?如何调用API接口来获取淘宝商品数据呢?本文将为大家详细解答。什么是API接口......
  • API接口技术开发心得,阿里巴巴中国站获得1688商品详情数据采集商品规格信息列表调用参
     1688商品详情API接口的重要性主要体现在以下几个方面:提供全面的商品信息:1688商品详情API接口可以提供详尽的商品信息,包括商品名称、规格、价格、产地、供应商信息等。这些信息对于用户来说是非常重要的,可以帮助用户全面了解商品的特点和属性,从而做出更明智的购买决策。......
  • Celery 使用 Ansible API 返回 None
    #在celerytask中加入#frommultiprocessingimportcurrent_process#current_process()._config={"semprefix":"/mp"}@app.taskdefcreate_task()frommultiprocessingimportcurrent_processcurrent_process()._config={"sempref......
  • C/C++ HOOK 全局 API
    全局Hook不一定需要用到Dll,比如全局的鼠标钩子、键盘钩子都是不需要Dll的,但是要钩住API,就需要Dll的协助了,下面直接放上Dll的代码,注意这里使用的是MFCDLL。//Test_Dll(mfc).cpp:定义DLL的初始化例程。//#include"stdafx.h"#include"Test_Dll(mfc).h"#ifde......
  • 一体化API研发协作赋能平台-API管理神器Apipost
    1.背景作为互联网工作者,不论是前端、后端还是测试,接口管理都是一个重要的任务。通常情况下,我们需要依赖以下解决方案来完成整个接口管理过程:使用Swagger管理API文档使用Postman调试API使用RAP或其他MockAPI工具使用JMeter进行API自动化测试可以看出,每个......
  • node restAPI 简单例子
      //第一版,node的httpp//consthttp=require('http');//constserver=http.createServer((req,res)=>{//if(req.url==='/'){//res.write('helloworld')//res.end();//}//if(req.url==='......
  • 从头学Java17-Stream API(二)结合Record、Optional
    StreamAPIStreamAPI是按照map/filter/reduce方法处理内存中数据的最佳工具。本系列教程由Record讲起,然后结合Optional,讨论collector的设计。使用Record对不可变数据进行建模Java语言为您提供了几种创建不可变类的方法。可能最直接的是创建一个包含final字段的final类。......
  • Vue 3.0 reactive/effect
    reactive.js:import{isObject}from"../utils";import{track,trigger}from"./effect";exportfunctionreactive(target){//判断target类型//如果是基本类型,则不将其转化成响应式if(!isObject(target))returntarget;constproxy......