helix-fetch
v1.1.1
Published
A lightweight, framework-independent TypeScript library designed for efficient front-end data fetching and caching. By creating an instance, it provides query and mutation function with all essential properties. And inside the instance you can provide bas
Maintainers
Readme
What is helix-fetch
A lightweight, framework-independent TypeScript library designed for efficient front-end data fetching and caching.
How to use
npm i helix-fetchimport { HelixFetch } from helix-fetch;i) Now create an instance.
const myFetch = new HelixFetch({
baseUrl = "https://jsonplaceholder.typicode.com",
setToken(){
// get your token from anywhere
const token = localStorage.getItem("auth")
if(token) return token; // will set to headers, "Authorization": token
return null
}
// The both baseUrl and setToken function are optional.
})And, this instance provides you two major method. One is query and another is mutation.
ii) Take a look for query.
✨ Option 1: For query.
const fun = async() => {
const result = await myFetch.query("/users") // above, we alredy set the base url.
console.log(result) // take a look what you get!
}
// Now all the data is cached. If the function get call again, it will return cached data.😍
// In this case, behind the seen - it autometically set headers
{
'content-type': 'application/json',
'Authorization': token
}✨ Option 2: For query.
const fun = async () => {
const result = await myFetch.query("/posts", {
headers: {
'Content-Type': 'application/json',
"auth": "aopz-pz-tf-zljyla-avrlu.",
"key": "value"
}
})
console.log(result)
}
// In this case, you are setting your custom headers.iii) Now see, how to do mutation.
✨ Option 1: For mutation.
const fun = async () => {
const payload = {
"name": "John Doe",
"age": 25,
"value": "key"
}
const result = await myFetch.mutation({
method: 'POST',
url: "/post",
body: payload,
})
console.log(result)
}✨ Option 2: For mutation.
// This one is just for include your custom headers.
const fun = async () => {
const payload = {
"name": "John Doe",
"age": 25,
"value": "key"
}
const result = await myFetch.mutation({
method: 'POST',
url: "/post",
body: payload,
headers: {
'Content-Type': 'application/json'
"autho": "i am a autho"
}
})
console.log(result)
}