Skip to main content

APISauce

  • axios http套件的簡易包裝
  • 所有回應都遵循相同的流程,成功與否都一樣,因此很方便使用

安裝APISauce

npm install apisauce

使用APISauce

  • 在專案根目錄底下建立一個api資料夾
  • 在這個api資料夾中新增一個js檔案:client.js
import { create } from 'apisauce';
const apiClient = create({
baseURL:'https://api2.aiot01.com';
});

export default apiClient;
  • 在這個api資料夾中新增一個js檔案:projects.js
import client from './apiClient';
const endpoint = '/projects';
const getProjects = () => client.get(endpoint);
export default {
getProjects,
};
  • 在實際使用的ProjectScreen中加入此api介面
import apiProjects from '../api/projects';
function ProjectScreen(){
const [projects, setProjects] = useState([]);
useEffect(() =>{loadData();},[]); //run this only ONCE
const loadData = async () => { //get data from the API server
const response = await apiProjects.getProjects();
setProjects(response.data);
}
}