Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
React : object is undefined when using loops and useState

I have this code

import React from 'react';
import { Button, Image, StyleSheet, Text, View } from 'react-native';

function App() {
  const firstCategory = [
    { id: 1, name: 'person1' },
    { id: 2, name: 'person2' },
    { id: 3, name: 'person3' },
    { id: 4, name: 'person4' },
  ];
  const [secondCategory, setSecondCategory] = React.useState([
    { id: 5, name: 'person5' },
    { id: 6, name: 'person6' },
    { id: 7, name: 'person7' },
    { id: 8, name: 'person8' },
  ]);

  React.useEffect(() => {
    setSecondCategory([]);
    for (var i = 0; i < firstCategory.length; i++) {
      setSecondCategory((secondCategoryArray) => [...secondCategoryArray, firstCategory[i]]);
    }
  },[]);



  return (
    <View>
      {secondCategory.map((item) => {
        return <Text>{item.name}</Text>;
      })}
    </View>
  );
}



export default App;

It is supposed to empty the secondCategory array and fill it with firstCategory array but when I console.log secondCategory array I get [undefined,undefined,undefined,undefined] and I get the error message 'cannot read property name of undefined'. I know that there are many other ways to achieve the wanted result but I want to know exactly the cause of this problem in this specific situation.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!