Tạo request api trong react

Tạo request api trong react hướng dẫn 2 cách truy cập đến api, đó là lệnh fetch của Javacript và thư viện Axios.


Trong thời đại lập trình tương tác hiện nay, việc request api rất là phổ biến. Bạn có thể request api đến các chức năng trong website của mình, hoặc reuest đến website khác trong cùng công ty. Hoặc cũng có thể request đến các dịch vụ public trên internet.

Ví dụ tạo request đến openweathermap.org để có thông tin thời tiết, tạo request đến unsplash.com để có các hình ảnh chia sẻ chất lượng cao, request api đến Google, Facebook, Youtube …

Request đến api cũng giống như request web, nhưng kết trả về không phải là khối code html, mà là dữ liệu có cấu trúc (json, xml)

Tạo request API như thế nào

Bạn có thể dùng cách cơ bản và đơn giản là lệnh fetch trong javascript để tạo request đến 1 tài nguyên api được cung cấp. Cách thứ hai là bạn có thể cài thư viện axios vào để thực hiện request api.

Sau đây là hướng dẫn cách đăng ký tài khoản , tạo app ở unsplash để sử dụng api của website này.

Đăng ký, tạo ứng dụng và lấy key trong Unsplash

Unsplash là 1 website chia sẻ hình ảnh chất lượng cao, miễn phí. Unsplash cũng cung cấp API để gọi từ xa.

1. Đăng ký: Vào  https://unsplash.com/developers   đăng ký với tư cách developers. Đăng ký xong thì login vào.

2. Tạo app : nhắp nút New Aplication để tạo, xong lưu access key và serect key

Tạo ứng dụng ở unsplash
Tạo ứng dụng ở unsplash
Tạo ứng dụng ở unsplash

3. Access key và Secret key hiện ra , lưu lại để dùng nhé

Key của unsplash cung cấp

4. Xem tài liệu hướng dẫn:

Vào Documentation => Search photo by keywords để xem cách dùng

Tài liệu hướng dẫn search hình ảnh ở unsplash

Form search picture

// FormSearchPic.js
import React from 'react';
class FormSearchPic extends React.Component{
  constructor(){
    super();
    this.state = {pictures:[]};
    this.tukhoa = React.createRef();
  }
  timhinh = (e) => {
    let tk = this.tukhoa.current.value;
    alert(tk);
  }
  render(){ const kq= <div>
      <form className="p-3 w-50 border border-primary m-auto">
        <p><input ref={this.tukhoa} className="form-control" 
        placeholder="Từ khóa"/></p>
        <button onClick={this.timhinh} type="button" 
        className="btn btn-primary">Tìm hình</button>
      </form>
      <div id="kqSeachPic" className="d-flex flex-wrap"></div> 
    </div>
    return (kq)
  }
} //class
export default FormSearchPic
//App.js
import FormSearchPic from "./FormSearchPic";
function App() {return (<FormSearchPic/>)}
export default App;

Tạo request API với lệnh fetch

– Code lại trong hàm tìm hình ở trên

timhinh = (e) => {
  let tk = this.tukhoa.current.value;
  let page = 1;
  let limit = 20;
  let key =`ACCESS_KEY_CUA_BAN`;
  let url =`https://api.unsplash.com/search/photos`; 
  url+=`?query=${tk}&page=${page}&per_page=${limit}&client_id=${key}`;
  fetch( url)
  .then( res => {
    if (!res.ok) throw Error(res.statusText);  
    return res.json(); 
   })
   .then( data => {
     console.log("results=", data.results);
     this.setState( {pictures: data.results});
   })
   .catch( error => console.log('Có lỗi nè : \n', error))
}//timhinh

– Code hiện các hình trong div#kqSeachPic

<div id="kqSeachPic" className="d-flex flex-wrap">
{ this.state.pictures.map( (h, index) => (
<div key={index} className="col-md-4">
<img src={h.urls.small} alt={h.alt_description} className="w-100"/>
</div>)
)
}
</div>

Tạo request API với thư viện Axios

Tham khảo thêm cách dùng axios ở địa chỉ : https://longnv.name.vn/lap-trinh-nodejs/su-dung-restful-api-nodejs

– Cài thư viện Axios: npm install axios

– Code trong hàm tìm hình ở trên với thư viện Axios

import axios from 'axios';

timhinh = async (e) => {
  let tk = this.tukhoa.current.value;
  let page = 1;
  let limit = 20;
  let key = `2OmauKfKbh3-9SJD3TCC-nKQ_5H8bvhTzCg3eyGpoBI`;
  let url =`https://api.unsplash.com/search/photos`; 
  url+=`?query=${tk}&page=${page}&per_page=${limit}&client_id=${key}`
  await axios.get(url)    
  .then( res => { 
     console.log("results=", res.data.results);
     this.setState( {pictures: res.data.results});
  })
  .catch( error =>  console.log('Có lỗi nè : \n', error));
}

Trên đây là ví dụ về cách dùng fetch và axios để tạo request api trong react. Bạn dựa vào các ví dụ cụ thể ở đây để request api ở các nơi khác nhé.