skip to Main Content

I need to refresh this function every 5 seconds and I am calling this function inside a map function.

I tried using setIntervel function to refresh the function every 5 seconds but it wosn’t successful because when I do that the variable are not been updated dynamically.

This the function

    let borderColor

    const changeBorderColor = (item) => {
        const today = new Date();
        const currentDate = format(today, 'yyyy-MM-dd HH:mm:ss');
        const redDate = format(new Date(item?.red_time || null), 'yyyy-MM-dd HH:mm:ss')
        const amberDate = format(new Date(item?.amber_time || null), 'yyyy-MM-dd HH:mm:ss')

        if(currentDate > redDate){
            borderColor = "order-list-right order-list-left-red"
        } else if (currentDate >= amberDate && currentDate < redDate){
            borderColor = "order-list-right order-list-left-amber"

        } else {
            borderColor = "order-list-right order-list-left-green"
        }
    }

this is where I call the function

{orderData?.data?.map((item) => {
      setInterval(() => changeBorderColor(item), 5000)
      return (
        <div 
           className={borderColor}
            onClick={() => orderItems(item)}
            key={item.id}
        >
       </div>
      )
})}

I am trying to change the borderColor variable every 5 seconds using this but I am unable to achieve this.

2

Answers


  1. This implementation SCREAMS code smell.

    Try archiving the desired effect using react best practices and create a new component which you create in your map function.
    Than add a useEffect() hook which calls a setInterval every five seconds.
    You can check this site: https://upmostly.com/tutorials/setinterval-in-react-components-using-hooks for a short tutorial.

    Login or Signup to reply.
  2. If you’re using React then you will have to use what it offers exactly to solve those kind of (very common) needs, you should not try to work around your framework in an attempt to circonvent having to learn more about it.

    The reason I’m saying that is useEffect. It is a core component of React and one of the first hooks your learn about in the documentation, this is for a reason.

    useEffect let’s you trigger logic that needs to happen only at certain points (ie: fetching data at initial mount, setting up constants, fetching when a particular value has changed) in your component’s life.

    In this case, you should start your interval in useEffect. It takes two parameters, the first is a function to call and the second is an array of values (generally states) that will trigger your function when they change. If no second argument is provided then your effect happens every render, but if you provide an empty list then it happens exactly once, when the component is first mounted.

    It could look like something below, for further details I strongly suggest you read the documentation.

    export default MyComponent() {
            
     const [bordercolor, setBordercolor] = useState("")
     
     function colorByItem(item) {
      // logic for single item depending on actual color
     }
    
     useEffect(() => {
      function myColorChange() {
        let newColor = "something"
        //logic to change color here
        setBordercolor(newcolor)
      }
      let interval = setInterval(myColorChange, 5000)
    
      return (() => { //we return a "cleanup" function that will be called on unmount, since we've set an interval we also need to clear it later.
       clearInterval(interval)
      })
     }, []) //empty array because we want to run this only to set the interval.
    
     return(
      {orderData?.data?.map((item) => {
       return (
        <div 
        className={colorByItem(bordercolor)}
        onClick={() => orderItems(item)}
        key={item.id}
        >
        </div>
       )
      })}
     )
    }
    

    I do think there are a LOT of things that you need to rethink about your code, the most obvious one: if you need logic for each of your map’s element then make another component, pass down a prop and handle that logic here so you can change it easily later on and add stuff to it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search