I followed most of codes from the site below.
https://dev.to/mmcshinsky/a-simple-approach-to-managing-api-calls-1lo6
it seems well-managed explanation but not enough me to understand.
There are 3 main files.
- provider.js = Defines how axios should connect with API.
import axios from 'axios';
import { handleResponse, handleError } from './response';
// my sample BASE URL
const BASE_URL = 'https://pokeapi.co/api/v2/pokemon/';
const getAll = (resource) => {
return axios
.get(`${BASE_URL}/${resource}`)
.then(handleResponse)
.catch(handleError)
}
const getSingle = (resource, id) => {
return axios
.get(`${BASE_URL}/${resource}/${id}`)
.then(handleResponse)
.catch(handleError);
};
const post = (resource, model) => {
return axios
.post(`${BASE_URL}/${resource}`, model)
.then(handleResponse)
.catch(handleError);
};
const put = (resource, model) => {
return axios
.put(`${BASE_URL}/${resource}`, model)
.then(handleResponse)
.catch(handleError);
};
export const apiProvider = {
getAll,
getSingle,
post,
put,
};
- core.js = Defines the reusable class that makes use of our provider.js with options.
import apiProvider from './provider';
export const ApiCore = (options) => {
//export class ApiCore {
// constructor(options) {
if (options.getAll) {
this.getAll = () => {
return apiProvider.getAll(options.url);
}
}
if (options.getSingle) {
this.getSingle = (id) => {
return apiProvider.getSingle(options.url, id);
}
}
if (options.post) {
this.post = (model) => {
return apiProvider.post(options.url, model);
}
}
if (options.put) {
this.put = (model) => {
return apiProvider.put(options.url, model);
}
}
//}
}
- response.js = handle response parsing, error handling...
export function handleResponse(response) {
if (response.results) {
return response.results;
}
if (response.data) {
return response.data;
}
return response;
}
export function handleError(error) {
if (error.data) {
return error.data;
}
return error;
}
Here is my question, If I want to call getAll API then how should I do that?
should I call the getAll API something like this?
const [data, setData] = useState();
const getData = async () => {
const result = await ApiCore(options.getAll);
setData(result);
}
would it be enough?
I am quite new to React. please guide me to use this API call.
Thank you
question from:
https://stackoverflow.com/questions/65882094/how-should-i-call-getall-method-within-my-structured-api-call 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…