I'm building an APP in React where I would like to consume an API for comments which allows crud rules. What I'm trying to build is a modular fetch that is implemented once and all the CRUD rules use the same fetch in one place where the base URL of the API is defined. Via the CRUD functionalities, I will just pass the endpoint I need and the related params and method. That will make life easier to use it around the APP when need it.
What I built first was my BaseAPI functionality as follow:
import { COMMENT_USER, COMMENT_PASS } from "./ConstAPI";
export const createCommentAPIQUery = urlGenerator => async (...params) => {
try {
const url = urlGenerator(...params);
const token = btoa(COMMENT_USER + ":" + COMMENT_PASS);
const credentials = {
method: "GET",
headers: new Headers({
Authorization: "Basic " + token,
"Content-Type": "application/json",
Accept: "application/json"
})
};
const response = await fetch(url, credentials);
const json = response.json();
return {
success: true,
...json
};
} catch {
return {
success: false,
result: [],
message:
"There is an issue to get data from server. Please try again later."
};
}
};
The issue above is that that will work when I use the GET but for the other CRUD will not as I need to pass a method and in case of a POST and PUT also stringify(). So the following CRUD functionalities were my attempt but as you will see that works only for the GET method and I need to find a solution for the rest of the methods:
import { createCommentAPIQUery } from "./BaseCommentAPI";
import { COMMENT_URL } from "./ConstAPI";
export const getAllComments = createCommentAPIQUery(
asin => `${COMMENT_URL}/comments/${asin}`
);
export const addComment = createCommentAPIQUery(body => {
`${COMMENT_URL}/comments`, (this.credentials.method = "POST");
this.credentials.body = JSON.stringify(body);
});
export const updateComment = createCommentAPIQUery((id, body) => {
`${COMMENT_URL}/comments/${id}`, (this.credentials.method = "PUT");
this.credentials.body = JSON.stringify(body);
});
export const deleteComment = createCommentAPIQUery(id => {
`${COMMENT_URL}/comments/${id}`, (this.credentials.method = "DELETE");
});
What I need is a good idea to make that work as I thought about it but actually I stack in it.
As it is now is generating an error as:
Expected an assignment or function call and instead saw an expression no-unused-expressions
So I need to figure out a good way to complete this idea and to avoid issues and bugs.
thisbinding. Try replacing the arrow functions with function declarations: Instead of this :()=>{}write your functions like this:function(){}awaitkeyword on the json response line too:const json = await response.json();thisis wrong either way