Giter Site home page Giter Site logo

p32929 / use-megamind Goto Github PK

View Code? Open in Web Editor NEW
2.0 1.0 0.0 14 KB

A simple react hook for managing asynchronous function calls with ease on the client side

Home Page: https://www.npmjs.com/package/use-megamind

License: MIT License

TypeScript 100.00%
async axios client-side-javascript data data-fetching easy fetch hooks javascript promise

use-megamind's Introduction

use-megamind

A simple react hook for managing asynchronous function calls with ease on the client side

Installation

npm install use-megamind

or

yarn add use-megamind

Motivation

I wanted to make a custom solution specially/not only for data fetching but also for any kinds of async operation. Of course, React Query ( https://github.com/tanstack/query ) is awesome ( even though I haven't tried it yet ) but I wanted to make something thats easier to implement, specially on an existing project & also doesn't need a lot of documentations to follow. Something that's small but does the job.

How to use

Example 1: Async function without parameters

"use client"

import useMegamind from "use-megamind"

function testAsyncFunction1() {
  return new Promise((res, rej) => {
    try {
      setTimeout(() => {
        res("Hello world")
      }, 1000);
    }
    catch (e) {
      rej(e)
    }
  })
}

export default function Home() {
  const { data, error, isLoading, call, clear } = useMegamind(testAsyncFunction1)

  return <div className="flex flex-col gap-y-10">
    <p>{JSON.stringify(data)}</p>
  </div>
}

Example 2: Async function with parameter(s)

functionParams: The async function parameters, one by one ( Default: null )

Yes, You will get intellisense like this

Screenshot (132)

"use client"

import useMegamind from "use-megamind"

function testAsyncFunction1(ms: number) {
  return new Promise((res, rej) => {
    try {
      setTimeout(() => {
        res("Hello world")
      }, ms);
    }
    catch (e) {
      rej(e)
    }
  })
}

export default function Home() {
  const { data, error, isLoading, call, clear } = useMegamind(testAsyncFunction1, {
    functionParams: [1000]
  })

  return <div className="flex flex-col gap-y-10">
    <p>{JSON.stringify(data)}</p>
  </div>
}

Example 3: Async function call on a button click

callRightAway: Whether the async function should be called on component mount ( Default: true )

"use client"

import useMegamind from "use-megamind"

function testAsyncFunction1(ms: number) {
  return new Promise((res, rej) => {
    try {
      setTimeout(() => {
        res("Hello world")
      }, ms);
    }
    catch (e) {
      rej(e)
    }
  })
}

export default function Home() {
  const { data, error, isLoading, call, clear } = useMegamind(testAsyncFunction1, {
    options: {
      callRightAway: false,
    }
  })

  return <div className="flex flex-col gap-y-10">
    <p>{JSON.stringify(data)}</p>
    <button onClick={() => {
      call(1000)
    }}>
      Call
    </button>
  </div>
}

Yes, passing functionParams is optional, unless you want to call the function on component mount

Example 4: Adding options

maxCalls: Maximum how many times the async function can be called ( Default: 'infinite' ). If maxCalls is 1, it caches the response.

minimumDelayBetweenCalls: Minimum delay between two calls for the async function ( Default: 0 ms )

debug: Show/hide logs ( Default: false )

callRightAway: Whether the async function should be called on component mount ( Default: true )

"use client"

import useMegamind from "use-megamind"

function testAsyncFunction1(ms: number) {
  return new Promise((res, rej) => {
    try {
      setTimeout(() => {
        res("Hello world")
      }, ms);
    }
    catch (e) {
      rej(e)
    }
  })
}

export default function Home() {
  const { data, error, isLoading, call, clear } = useMegamind(testAsyncFunction1, {
    options: {
      callRightAway: false,
      debug: false,
      maxCalls: 1,
      minimumDelayBetweenCalls: 1000 // ms
    }
  })

  return <div className="flex flex-col gap-y-10">
    <p>{JSON.stringify(data)}</p>
    <button onClick={() => {
      call(1000)
    }}>
      Call
    </button>
  </div>
}

Example 5: Listening to the async function events

"use client"

import useMegamind from "use-megamind"

function testAsyncFunction1(ms: number) {
  return new Promise((res, rej) => {
    try {
      setTimeout(() => {
        res("Hello world")
      }, ms);
    }
    catch (e) {
      rej(e)
    }
  })
}

export default function Home() {
  const { data, error, isLoading, call, clear } = useMegamind(testAsyncFunction1, {
    options: {
      callRightAway: false,
      debug: false,
      maxCalls: 1,
      minimumDelayBetweenCalls: 1000 // ms
    },
    events: {
      onError(error) {
          // set your states here if needed
      },
      onLoadingChange(isLoading) {
          // set your states here if needed
      },
      onLoadingFinished() {
          // set your states here if needed
      },
      onLoadingStart() {
          // set your states here if needed
      },
      onSuccess(data) {
          // set your states here if needed
      },
    }
  })

  return <div className="flex flex-col gap-y-10">
    <p>{JSON.stringify(data)}</p>
    <button onClick={() => {
      call(1000)
    }}>
      Call
    </button>
  </div>
}

Example 6: Other things

clear: Clears the state of the hook. Resets data, error, and loading states.

reset: Resets the state of the hook including cache and call counter. Clears data, error, and loading states. Clears the cached result and resets the call counter.

"use client"

import useMegamind from "@/lib/useMegamind";

function testAsyncFunction1(ms: number): Promise<string> {
  return new Promise((res, rej) => {
    try {
      setTimeout(() => {
        res("Hello world")
      }, ms);
    }
    catch (e) {
      rej(e)
    }
  })
}

export default function Home() {
  const { data, error, isLoading, call, clear, reset } = useMegamind(testAsyncFunction1, {
    options: {
      callRightAway: false,
      debug: false,
      maxCalls: 1,
      minimumDelayBetweenCalls: 1000 // ms
    },
    events: {
      onError(error) {
        // set your states here if needed
      },
      onLoadingChange(isLoading) {
        // set your states here if needed
      },
      onLoadingFinished() {
        // set your states here if needed
      },
      onLoadingStart() {
        // set your states here if needed
      },
      onSuccess(data) {
        // set your states here if needed
      },
    }
  })

  return <div className="flex flex-col gap-y-10">
    <p>{JSON.stringify(data)}</p>
    <button onClick={() => {
      call(1000)
    }}>
      Call
    </button>

    <button onClick={() => {
      clear()
    }}>
      Clear
    </button>

    <button onClick={() => {
      reset()
    }}>
      Reset
    </button>
  </div>
}

if you just want to clear the states and keep the cache, use clear() but to clear everything including cache use reset()

& Finaly, If you're using TypeScipt, if you define the return types in the async function, you will get better intellisense like this:

Screenshot (133)

Contribution

If you want to contribute to this project like adding feature, fixing bugs etc, please open an issue before submitting any pull requests.

License

MIT License

Copyright (c) 2024 Fayaz Bin Salam

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

use-megamind's People

Contributors

p32929 avatar

Stargazers

 avatar  avatar

Watchers

 avatar

use-megamind's Issues

Rename option callRighAway

I think callRighAway is not an understandable name for the option. It can be renamed as callOnMount or callImmedietly or something else. Thanks

image

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.