Skip to content
Advertisement

How can I create conditions on multiple array objects to handle errors in React?

I have an array object called containtemps. It has a property value called modDate.

I extract the boolean value of the temperror variable by comparing the time based on the modDate property value among several objects in containtemps.

So, by putting temperror variables 1, 2, and 3 in the error variable, if any one of them is true, the NotError component is rendered, and when all of them are false, the Error component is rendered.

But looking at my code, this seems inefficient because there are too many duplicates.

As you can see, temperror0 and temperror1 and temperror2, The code that creates the variable is duplicated. How can I get rid of these duplicate values ​​in one piece of code?

this is my code

    const containtemps = [
        {
            modDate:"2022-09-22T04:48:00.000Z"
        },
        {
            modDate: null
        },
        {
            modDate:"2022-09-22T04:5:00.000Z"
        }
    ]

      this is duplicated code

      let curTime = new Date()
      curTime.setHours(curTime.getHours() - 6)


    const tempModate0 = containtemps[0]?.modDate;

    let tempmodDate0 = new Date(tempModate0)

    let temperror0 = curTime.getTime() <= tempmodDate0.getTime() ? false : true


    const tempModate1 = containtemps[1]?.modDate;


    let tempmodDate1 = new Date(tempModate1)

    let temperror1 = curTime.getTime() <= tempmodDate1.getTime() ? false : true



    
    const tempModate2 = containtemps[2]?.modDate;


    let tempmodDate2 = new Date(tempModate2)

    let temperror2 = curTime.getTime() <= tempmodDate2.getTime() ? false : true

    const error =

    temperror0 ||
    temperror1 ||
    temperror2 ;

    ;


    return (

    !error ?
    (
    <NotError>
    notError
    </NotError>

    )
    :
    (
        <Error>
        error
        </Error>)

    )

Advertisement

Answer

You can use some function inside your array. It will return true if it finds at least one result matching your expression. Here you need the opposite expression >

const curTime = new Date();
const error = containtemps.some(t => t.modDate && curTime.getTime() > new Date(t.modDate).getTime())
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement