Giter Site home page Giter Site logo

glamboyosa / mey Goto Github PK

View Code? Open in Web Editor NEW
18.0 3.0 0.0 435 KB

A react package that exports hooks for handling the request lifecycle.

Home Page: https://www.npmjs.com/package/mey

HTML 16.70% TypeScript 79.37% CSS 3.93%
hooks react data-fetching fetch data react-native

mey's Introduction

mey

A react package that exports hooks for handling the request lifecycle

NPM JavaScript Style Guide

Motivation

This package was created for people who don't want to go through the chore of handling the request lifecycle but don't want to reach for a big data fetching library. A lot of people do not need the complexity of a big library, the project's aren't complex enough to warrant such overhead but equally are tired of handling the request lifecycle and the questions that come with it such as:

  • "should i use useReducer or useState ?"
  • "do i have different slices of state or a state object? which is cleaner?" This package aims to take all that pain away and exports two hooks to handle it all useFetch and useMutation

Install

npm install --save mey
yarn add mey

it is written in TypeScript so no need to install types.

useFetch Usage

import { useFetch } from "mey";

const { data, loading, error, refetch } = useFetch(
  "https://jsonplaceholder.typicode.com/posts"
);
console.log("the data is:");
console.log(data);
if (!data && loading) {
  return <div> loading </div>;
}
if (error) {
  return <div> {error} </div>;
}
return <div>{data.map((el: any) => el.title)[0]}</div>;

useMutation Usage

import  {useMutation}  from "mey";

const { data, loading, error, handleRequest } = useMutation(
  "https://jsonplaceholder.typicode.com/posts", "post"
);
const submitHandler = () => {
const randomNumber = Math.random() * 100;
const body = {
  randomNumber
}
handleRequest(body);
};
return (
  <div>
  <p> generate a new random number: {data && !error ? data : error } </p>
  <button disabled={loading} onClick={submitHandler}> click me </button>
)

Typing the response

If you want your response typed both useFetch and useMutation accept a generic in which you'd pass in the type. You can view in example/src/index.tsx or an example useFetch implementation down below:

import { useFetch } from "mey";
const { data, loading, error, refetch } = useFetch<
  { body: string; userId: number; id: number; title: string }[]
>("https://jsonplaceholder.typicode.com/posts");
console.log("The data is:");
console.log(data);
if (!data && loading) {
  return <div> loading </div>;
}
if (error) {
  return <div> {error} </div>;
}
return <div>{data.map((el) => el.title)[0]}</div>;

Global Config

Mey ships with a provider called MeyProvider that you would wrap around <App/> or <Component/> in your root, entry point of your project as the case may be. MeyProvider accepts a single prop BaseURL that is the primary URL you would be making calls to. the point is to eliminate typing the same base path in every component that uses a hook. you'd simply now pass the path you're trying to hit e.g "/posts" which would translate to "https://yourbasepath.com/posts"

Global Config Example

import "./index.css";
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { MeyProvider } from "mey";
ReactDOM.render(
  <MeyProvider BaseURL="https://yourbasepath.com">
    <App />
  </MeyProvider>,
  document.getElementById("root")
);

Extended useFetch Usage

import { useFetch } from "mey";

const { data, loading, error, refetch } = useFetch(
  "https://jsonplaceholder.typicode.com/posts",
  {
    authorization: " bearer authentication-token",
    xpth: "xsssf",
  }
);
if (!data && loading) {
  return <div> loading </div>;
}
if (error) {
  return <div> {error} </div>;
}
return <div>{data.map((el: any) => el.title)[0]}</div>;

Extended useMutation Usage

import  {useMutation}  from "mey";

const { data, loading, error, handleRequest } = useMutation(
  "https://jsonplaceholder.typicode.com/posts", "post", {
    authorization: " bearer authentication-token",
    xpth: "xsssf",
  }
);
const submitHandler = () => {
const randomNumber = Math.random() * 100;
const body = {
  randomNumber
}
handleRequest(body);
};
return (
  <div>
  <p> generate a new random number: {data && !error ? data : error } </p>
  <button disabled={loading} onClick={submitHandler}> click me </button>
)

useFetch API

const { data, loading, error, refetch } = useFetch(url, headers);

Parameters

  • url: the URL path you want to fetch.
  • headers: (optional) an object representing the values you want to set on the request header.

Values

  • data: data for the given path.
  • loading: a boolean representing whether the request is loading or not.
  • error: a string representing a potential error thrown.
  • refetch: a function that refetches data.

useMutation API

const { data, loading, error, handleRequest } = useMey(
  url,
  requestType,
  headers
);

Parameters

  • url: the URL path you want to fetch.
  • requestType: a union of string types representing the type of mutation you want to carry out i.e put, post & delete.
  • headers: (optional) an object representing the values you want to set on the request header.

Values

  • data: data for the given path.
  • loading: a boolean representing whether the request is loading or not.
  • error: a string representing a potential error thrown.
  • handleRequest: a function that handles dispatching requests. it accepts a body value. if the body value is not an object it stops execution and prints an error message to the console.

Support

Have a question ? send me an email @ [email protected] or hit me up on twitter. also feel free to checkout my portfolio

License

MIT © glamboyosa

mey's People

Contributors

glamboyosa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

mey's Issues

[Feature]: support more headers

problem: current implementation only supports Authentication header, it is possible the user might want to pass more headers.
fix: allow the user pass an array with an object to represent the headers object.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.