Home > database >  props changes but variable which depends of props not
props changes but variable which depends of props not

Time:01-24

there is variable currentHour which needs changes when prop localTime changes but when i do another request localTime changes but currentHour no.

i tried hooks but i think i didnt use it properly

import React, { useEffect, useMemo, useState } from 'react'
import HourData from './HourData'

const HourDataList = ({hoursData, localTime}) => {
  
  //new Date(localTime*1000).getHours()

  let currentHour = new Date(localTime*1000).getHours()
 
 
  console.log(localTime)
  console.log(currentHour)  
  const dataArr = []

  for (let i = currentHour; i < currentHour  6; i  ) {
    dataArr.push(hoursData[i])
  }
  

  return (
    <div className='flex flex-row mb-3'>
              
              {dataArr.map((data, i) => <HourData key={i} data={data}/>)}
              
              
    </div>
  )
}

export default HourDataList

CodePudding user response:

Use react state and useEffect instead, to be listen to changes of localTime and force component to rerender

like this :

import React, { useEffect, useMemo, useState } from 'react'
import HourData from './HourData'

const HourDataList = ({hoursData, localTime}) => {
    
    const [dataArr,setDataArr] = useState([])

    useEffect(()=>{
        let currentHour = new Date(localTime*1000).getHours()
        const arr = []

        for (let i = currentHour; i < currentHour  6; i  ) {
            arr.push(hoursData[i])
        }
        setDataArr(arr)
    },[localTime])

    return (
        <div className='flex flex-row mb-3'>

            {dataArr.map((data, i) => <HourData key={i} data={data}/>)}


        </div>
    )
}
export default HourDataList

CodePudding user response:

If your component does not re-render, your variable localTime wont be calculated again.

There are two common reasons why React might not update a component even though its props have changed:

The props weren't updated correctly via setState, or The reference to the prop stayed the same.

So either you have a look at these two points and change the re-rendering behavior of your component, or you use the useEffect hook as shown in the other answer.

  • Related