Create tasks to perform effect easier with React Hooks
npm install tasook> Create tasks to perform effect easier with React Hooks
 
``bash`
npm install --save tasook
React Hooks provide useEffect for perform side effects, but we need :
1. Reduce the boilerplate code when handling async operations
2. 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.
`js
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 (
disabled={loadingA}
onClick={
() => {
taskA('Mark@' + (new Date()))
.then(()=> {
console.log('taskA returns what effectA returns')
})
}
}
>
{loadingA ? 'Loading...' : 'Reload effectA'}
export default App
``
MIT © kpaxqin