⌨️
Web Design
  • Index
  • Front End
    • Front End Index
  • HTML/CSS/JS
    • HTML Index
      • Page layout
      • Form
      • Image Optimization
    • CSS Index
      • CSS Selectors
        • Selectors
        • Combinators
        • Attribute Selectors
        • Pseudo classes
      • CSS Cascade and Inheritance
        • Cascade
        • Inheritance
      • Specificity
      • Box Model
      • CSS Clearfix
      • Responsive Meta Tag
      • Flexbox Layout
      • Grid Layout
      • CSS Naming Rules
        • Golden Guidelines for Writing Clean CSS
        • BEM
        • Rules
      • Frameworks & Libraries
    • JS Index
      • JS loading
      • Modules
      • Js Array Common Method 1
      • Js Array Common Method 2
      • Custom attributes on the element
      • Operator
      • Parse a JSON Date in JavaScript
      • Importmap
  • Git
    • Git Index
    • Initialize a Repository
    • Top 20 Git Commands With Examples
  • UML
    • UML Class
  • React
    • Index
      • setState async issue
      • Redux
      • Axios
      • useState update in A Timeout
  • WebGL
    • WebGL Index
  • Back End
    • Back-End Index
      • Knex
      • Bookshelf
        • bookshelf install
        • Bookshelf only returns one row
      • Server side init flow
      • Install Wordpress on Ubuntu 22.04 with a LAMP Stack
  • React Native
    • React Native Index
      • Dynamically changing Image URLs in React Native
  • Expo
    • EAS build config
Powered by GitBook
On this page

Was this helpful?

  1. React
  2. Index

useState update in A Timeout

Use ref to save the newest value of variable

  function App () {
    const ref = useRef()
    ref.current = {distance, nextWayPointId, nextWayPoint}
  
    useEffect(()=>{
    
    },[nextWayPointId])

    useEffect(()=>{
      let enemyTimeID = setTimeout(()=>{
        const currentPosition = [location.left, location.top]
        setDistance(getDistance(currentPosition,ref.current.nextWayPoint))
  
        if (ref.current.distance < 1) {
          setNextWayPointID(prev=>prev+1)
          setNextWayPoint(waypath.stage1[ref.current.nextWayPointId])
          console.log(ref.current.nextWayPointId)
          console.log(ref.current.nextWayPoint)
        }else {
          const lengthX = nextWayPoint[0] - currentPosition[0]
          const lengthY = nextWayPoint[1] - currentPosition[1]
          
          const step = Math.round(ref.current.distance/speed)
          console.log(ref.current.distance)
    
          const top = location.top + (lengthY / step)
          const left = location.left+ (lengthX / step)
          setLocation({top,left})
        }
      },100)
  
      return ()=>{
        clearTimeout(enemyTimeID);
      }
    },[location,nextWayPoint])
  }
PreviousAxiosNextWebGL Index

Last updated 2 years ago

Was this helpful?