Skip to content

banyudu/use-outdated-effect

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

use-outdated-effect

useEffect with the outdated and unmounted functions as parameters

With useOutdatedEffect, you can check whether the dependency variables changed after async operations, then cancel the proceeding operations as you wish.

install

    npm install --save use-outdated-effect

usage

import React, { FC, useState } from 'react'
import useOutdatedEffect from 'use-outdated-effect'
import axios from 'axios'

const App = (props) => {
  const { id } = props

  const [dataSource, setDataSource] = useState(null)

  useOutdatedEffect(async (outdated, unmounted) => {
    const { data } = await axios.get(`/api/mydata/${id}`)

    if (outdated()) { // check whether dependencies changed. In this example, it's the id variable
      // id changed, stop the current operations
      return
    }

    if (unmounted()) { // check whether component is unmounted
      // component destroied, stop the current operations
      return
    }

    setDataSource(data)
  }, [id])

}

About

useEffect with an `outdated` and `mounted` functions and parameters

Resources

License

Stars

Watchers

Forks

Packages

No packages published