Typescript react http request

Send HTTP GET Request for Consuming a REST API with Axios in Ionic 4 App (Based on TypeScript & React Hooks)

In this quick tutorial we’ll see by example how to consume a third-party API using Axios inside an Ionic 4 project based on TypeScript and React. We’ll see how to:

  • Install and use Axios for sending HTTP GET requests in TypeScript and React,
  • Consume a third-party REST API,
  • Use React Hooks like useState and useEffect,
  • Display the data using IonList and IonItem components,
  • Create buttons using IonButton.

The useState() and useEffect() methods are built-in React Hooks introduced in React 16.8+; they enable developers to use state and other React features in functional React components.

Let’s get started with the prerequisites!

You need to have the following:

  • Node and NPM installed on your machine,
  • Knowledge of TypeScript and React,
  • Ionic CLI v5+ and a Ionic/React project.

We’ll make use of a the third-party API available from NewsAPI.org. You should register for a free account and get an API key to access the service otherwise you can also consume any available REST API of your choice.

Читайте также:  Php json encode boolean

Step 1 – Installing Axios in Your Ionic/React Project

In this step, we’ll see how to install Axios in our Ionic/React project.

Provided that you have already created your Ionic/React project, head back to your terminal and navigate inside the project’s root folder and install Axios from npm as follows:

$ cd ./App $ npm install axios --save 

Step 2 – Sending an HTTP GET Request with Axios

In this step, we’ll use Axios to send a GET request for consuming the third-party API.

If you have generated your Ionic project based on the sidemenu template, you’ll already have a home page.

Go ahead and open the src/pages/Home.tsx file, and import the necessary APIs i.e axios and IonButton as follows:

import < IonButton, IonList, IonItem >from '@ionic/react'; import axios from 'axios'; 

Next, define the apiKEY and endpoint variables:

const apiKEY = ""; const endpoint = `https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=$`; 

Next, define the following method

Next, define the sendGetRequest() method as follows:

const sendGetRequest = () => < return axios(< url: URL, method: 'get' >).then(response => < console.log(response); return response.data; >) >; 

We call the axios() method to send a GET request to the REST API endpoint.

Step 3 – Building the UI with React Hooks (useState & useEffect) and Ionic Components (IonList, IonItem and IonButton)

In this step, we’ll build the UI of our home page. We’ll use Ionic components such as IonList, IonItem and IonButton, React Hooks such as useState and useEffect.

Inside the HomePage functional component and call the useState method to create a state variables named items as follows:

const HomePage: React.FunctionComponent = () => < const [items, setItems] = React.useState([]); 

useState() returns the state variable, which has the empty array as its initial value and a function that we can use to change the value of the variable. We use destructuring assignment to unpack the values from the returned pair into distinct variables (i.e. articles and setArticles() ).

Next, call the sendGetRequest() method inside the useEffect hook to consume the REST API:

const HomePage: React.FunctionComponent = () => < const [items, setItems] = React.useState([]); React.useEffect(() => < sendGetRequest().then(data =>setItems(data.articles)); >, []); ``` 

We use use the useEffect() hook to perform a side effect in our component. The side effect is consuming data from the REST API.

The useEffect() hook is equivalent to calling the componentDidMount , componentDidUpdate and componentWillUnmount lifecycle methods combined in class-based components.

Next, itertate over the items array and render the data fetched from the REST API as folows:

const HomePage: React.FunctionComponent = () => < const [items, setItems] = React.useState([]); React.useEffect(() => < sendGetRequest().then(data =>setItems(data.articles)); >, []); return ( <>     Home     < items.map(item => < return (   color="primary" slot="end">See article  ); >) >  ); >; 

This is a screenshot of the home page UI:

React Ionic example

Concusion

In this quick example, we’ve seen how to use Axios to send GET requests to consume a REST API inside an Ionic/React app based on TypeScript.

We’ve used React Hooks like useState and useEffect and Ionic 4+ components like IonList, IonItem and IonButton.

Источник

Typescript react http request

Make sure to install axios before using the code samples in the article.

You can install axios by opening your terminal in your project's root directory and running the npm install axios command.

Copied!
# 👇️ if you need to initialize a package.json file npm init -y # ✅ with NPM npm install axios # ✅ with YARN yarn add axios

Here is an example of an HTTP GET request using axios in TypeScript.

Copied!
import axios from 'axios'; type User = id: number; email: string; first_name: string; >; type GetUsersResponse = data: User[]; >; async function getUsers() try // 👇️ const data: GetUsersResponse const data, status > = await axios.getGetUsersResponse>( 'https://reqres.in/api/users', headers: Accept: 'application/json', >, >, ); console.log(JSON.stringify(data, null, 4)); // 👇️ "response status is: 200" console.log('response status is: ', status); return data; > catch (error) if (axios.isAxiosError(error)) console.log('error message: ', error.message); return error.message; > else console.log('unexpected error: ', error); return 'An unexpected error occurred'; > > > getUsers();

If you get the error "Cannot find module 'axios'", click on the following article and follow the installation instructions.

We defined the type for the response we expect from the server and provided it when using the axios.get method.

The first argument the axios.get() method takes is the URL.

Copied!
axios.get(url, config)

The second argument is a request config object and is not required.

I only included the second argument because you might be making HTTP GET requests to an API that requires authorization. In this case, you might need to set an Authorization header.

If you need to check the response schema, look at this section of the axios GitHub repository.

Copied!
// `data` is the response from the server data: >, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the HTTP headers that the server responded with // All header names are lowercase and can be accessed using the bracket notation. // Example: `response.headers['content-type']` headers: >, // `config` is the config that was provided to `axios` for the request config: >, // `request` is the request that generated this response request: > >

We destructured the data property from the axios response schema.

Copied!
const data, status > = await axios.getGetUsersResponse>( 'https://reqres.in/api/users', headers: Accept: 'application/json', >, >, );

The data property is the response that was provided by the server.

Another property you might need to use from the response object is status . It represents the status code from the server's response, e.g. 200 or 404 .

Axios includes a type guard for errors which we used in our catch method.

Copied!
catch (error) if (axios.isAxiosError(error)) console.log('error message: ', error.message); return error.message; > else console.log('unexpected error: ', error); return 'An unexpected error occurred'; > >

If the error is an axios error, we can safely access the message property to get the error message.

Otherwise, the error is typed as unknown and we have to manually check before accessing any properties.

What you might have noticed is that axios automatically parses the JSON from the response as opposed to the built-in fetch() method.

We directly have the parsed response stored in the data variable.

If you want to use the built-in fetch module to make HTTP requests in TypeScript, check out my other article.

# Making HTTP POST requests with Axios in TypeScript

Let's look at an example HTTP POST request made with axios in TypeScript.

I'll post the entire code snippet and then we'll go over it.

Copied!
import axios from 'axios'; type CreateUserResponse = name: string; job: string; id: string; createdAt: string; >; async function createUser() try // 👇️ const data: CreateUserResponse const data, status > = await axios.postCreateUserResponse>( 'https://reqres.in/api/users', name: 'John Smith', job: 'manager' >, headers: 'Content-Type': 'application/json', Accept: 'application/json', >, >, ); console.log(JSON.stringify(data, null, 4)); console.log(status); return data; > catch (error) if (axios.isAxiosError(error)) console.log('error message: ', error.message); // 👇️ error: AxiosError return error.message; > else console.log('unexpected error: ', error); return 'An unexpected error occurred'; > > > createUser();

We used the axios.post method to make an HTTP POST request.

Copied!
axios.post(url, data, config)

We passed the type of the expected response as a generic to the axios.post() method.

Copied!
const data, status > = await axios.postCreateUserResponse>( 'https://reqres.in/api/users', name: 'John Smith', job: 'manager' >, headers: 'Content-Type': 'application/json', Accept: 'application/json', >, >, );

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

React Query, Axios, Typescript example: get, post, put, delete - useQuery, useMutation, error handling

bezkoder/react-query-axios-typescript

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

React Query with Axios and Typescript example

React Client with React Query and Axios (Typescript) to make CRUD requests to Rest API in that:

  • React Query Axios Typescript GET request: get all Tutorials, get Tutorial by Id, find Tutorial by title
  • React Query Axios Typescript POST request: create new Tutorial
  • React Query Axios Typescript PUT request: update an existing Tutorial
  • React Query Axios Typescript DELETE request: delete a Tutorial, delete all Tutorials

react-query-axios-typescript

For instruction, please visit:

Fullstack with Node Express:

Fullstack with Spring Boot:

Integration (run back-end & front-end on same server/port)

This project was bootstrapped with Create React App.

About

React Query, Axios, Typescript example: get, post, put, delete - useQuery, useMutation, error handling

Источник

Оцените статью