Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I add the first to the array in useState in React?

I have an array object called tempArr.

When I run a function called fetchLifeCycle, i want to act setPickerItems(tempArr); is mandatory first, and then setPickerItems([…tempArr, { label: ‘Not selected’, value: "NONE" }]) .

As a result, { label: ‘not selected’, value: "NONE" } was added at the end.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But I want to add that object to the first object of pickerItems. How do I do that?

this is my code

    tempArr = [
            { label: "hi", value: 'egg' },
            { label: "bye", value: 'insect' },
            { label: "woo", value: 'pest' },
            { label: "pick", value: 'hambuger' },

    ]


  const [pickerItems, setPickerItems] = useState([])


  const fetchLifeCycle = () => {

    setPickerItems(tempArr);
    setPickerItems([...tempArr, { label: '선택안함', value: "NONE" }])

}

expected answer

pickerItems = [
            { label: '선택안함', value: "NONE" }
            { label: "hi", value: 'egg' },
            { label: "bye", value: 'insect' },
            { label: "woo", value: 'pest' },
            { label: "pick", value: 'hambuger' },
    ]

>Solution :

tempArr = [
            { label: "hi", value: 'egg' },
            { label: "bye", value: 'insect' },
            { label: "woo", value: 'pest' },
            { label: "pick", value: 'hambuger' },

    ]
    
const updated = [{ label: '선택안함', value: "NONE" }, ...tempArr]

console.log('updated', updated)

You just have to reverse the order:

setPickerItems([{ label: '선택안함', value: "NONE" }, ...tempArr])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading