tasook
v1.0.0
Published
Create tasks to perform effect easier with React Hooks
Downloads
1
Readme
tasook
Create tasks to perform effect easier with React Hooks
Install
npm install --save tasook
Overview
React Hooks provide useEffect
for perform side effects, but we need :
- Reduce the boilerplate code when handling async operations
- Solution to de-couple the trigger & consume of effects, to avoid consume logics in useEffect function, like Dan mentioned in he's twitter
So we build createTask
& useTask
, to enable us consume data first, then trigger the async operation when need.
Usage
import React, { useEffect } from 'react'
import { effectA, effectB } from './effects';
import { createTasks, createTask, useTask } from 'tasook'
const taskA = createTask(effectA)
const tasks = createTasks({ // create multiple tasks
effectB,
})
const App = () => {
// consume task with useTask
const [dataA, errorA, loadingA] = useTask(taskA)
const [dataB] = useTask(tasks.effectB)
useEffect(() => {
// only trigger effects in useEffect, do not consume effect results here
taskA('John') // taskA will pass all arguments to effectA
tasks.effectB('Kpax')
}, [])
return (
<div>
hello Tasook
<div>
effectA: {dataA}
<br/>
effectB: {dataB}
</div>
<p>
<button
disabled={loadingA}
onClick={
() => {
taskA('Mark@' + (new Date()))
.then(()=> {
console.log('taskA returns what effectA returns')
})
}
}
>
{loadingA ? 'Loading...' : 'Reload effectA'}
</button>
</p>
</div>
)
}
export default App
License
MIT © kpaxqin