1.0.4 • Published 3 years ago

use-async-resource-with-recoil v1.0.4

Weekly downloads
8
License
MIT
Repository
github
Last release
3 years ago

use-async-resource-with-recoil

Installation

 npm i use-async-resource-with-recoil

How to use ?

	....
	import useAsyncResourceWithRecoil from  "use-async-resource-with-recoil";
	import React, {Suspense} from "react"
	
	//inside the component
	...
	const callOnlyOnFetchAgain = false 
	const {
		dataReader,
		data,
		fetchAgain,
		dataSetter
			} = useAsyncResourceWithRecoil(
				apiFunction,
				argumentsOfapiFunction,
				recoilAtom,
				callOnlyOnFetchAgain
			)

	//inside the jsx
	....
	<Suspense fallback="Loading data..">
		<Data dataReader={dataReader} />
	</Suspense>

	//inside <Data /> Component
	...
	function Data({dataReader}){
		const data = dataReader()
		return (
			<>
			  {
			    data.map(d => <div key={d.id}> {d.value} </div>)
			  }
			</>
		)
	}

Arguments

The useAsyncResourceWithRecoil hook accepts the following arguments:

NameTypeDescriptionDefault ValueRequired
apiFunctionFunctionAccepts an asynchronous function to call backend APIYes
argumentsOfapiFunctionArrayAccepts an array of arguments for apiFunction eg: apiFunction(arg1, arg2, arg3) given as [arg1, arg2, arg3]Yes
recoilAtomRecoilStateAccepts a RecoilState that created using atom() from recoilYes
callOnlyOnFetchAgainBooleanif it is given as true then the apiFunction won't execute during the initialization and only executed on calling fetchAgainfalseNo

Results

After being called, the useAsyncResourceWithRecoil hook returns a result object with the following properties.

NameTypeDescription
dataReaderFunctioninvoke this function get the API results
fetchAgainFunctioninvoke this function to get results the API function again on dataReader()
dataRecoilStateValuevalue of the RecoilState or Recoil Atom
setDataFunctionA function to set the value of RecoilState

Example app

Example 1