1.0.5 • Published 12 months ago

react-use-fun v1.0.5

Weekly downloads
-
License
GPL-3.0
Repository
github
Last release
12 months ago

use-fun

React hook to provide a function that is able to access actual states in an anonymous context.

Install

yarn add react-use-fun
# or
npm i react-use-fun --save

Usage / Example:

export default function Example(){
    const [start, setStart] = useState(true)

    const checkCondition = useFun(  () => {
        return start
    });

    async function longRunning(){
        console.log('processing started')

        //while(start)){ //will not work due to cached start value (Also see: CallByValue)
        while(checkCondition()){
            //do some weird processing
            await delay(1000)
            console.log('processing...')
        }
        console.log('processing ended.')
    }

    useEffect(() => {
        if (start) {
            longRunning().then()
            setStart(false)
        }
        else{
            console.log('processing aborted')
        }
    }, [start])

    return <div>check console logs</div>
}

Parameters

the returned function takes one parameter. For example...

    const [selection, setSelection] = useState(null)

    const onSelectionChanged = useFun(  ( {id: number, data: any} ) => {
        if (!selection) {
            setSelection(data)
            return console.log(`selection changed to id: ${id}`)
        }
        console.log('selection already set')
    });

    // call
    callInSomeFunction = () => {
        onSelectionChanged({id: 1, data: [1, 2, 3]}) 
    }   
    
1.0.5

12 months ago

1.0.4

12 months ago

1.0.3

12 months ago

1.0.2

12 months ago

1.0.1

12 months ago

1.0.0

12 months ago