808Code
808Code

Reputation: 75

My State variable in React with data type array with a setter that should be acing as push() to the array not working

Code:

const [departmentNames,setDepartmentNames]=React.useState([]);


console.log(typeof(departmentNames));
      Object.keys(departments).forEach(
      (key)=>{
              console.log("department="+departments[key].name)
              setDepartmentNames(departments[key].name);        
             }
                                       );

in first line of code i created an departmentNames as an array but in line

console.log(typeof(departmentNames));

the output is string .

how do i make departmentNames an ARRAY with its setter as push().

Upvotes: 0

Views: 964

Answers (3)

Vivek
Vivek

Reputation: 104

You can use map function to return name from the department array object

  const [departmentNames, setDepartmentNames] = React.useState<any>([]);

  const deptData = [{ key: 1, name: 'IT' }, { key: 2, name: 'Corp' }];
  useEffect(() => {
    setDepartmentNames(deptData.map(d => d.name));
  }, []);

Upvotes: 0

Eduardo Farrera
Eduardo Farrera

Reputation: 206

The type showing as string might be because you are changing the type afterwards.

About using setDepartmentsNames setter as a push... the short answer would be that you can't because like you said it is a setter function so it sets the value of the variable. But you have two options to accomplish what you want:

Expanding the old data and adding new data:

Object.keys(departments).forEach(
   (key) => {
      console.log('department=' + departments[key].name)
      setDepartmentNames((departmentNames) => [...departmentNames,departments[key].name])
   })

Or creating an array an saving it to the state:

const departmentsNamesArray = []
Object.keys(departments).forEach((key) => {
    console.log('department=' + departments[key].name)
    departmentsNamesrray.push(departments[key].name)
})
setDepartmentNames(departments[key].name)

Upvotes: 0

Jishnu Vijayan
Jishnu Vijayan

Reputation: 103

How about you create a new Array and then use the setter to set the state once you're done creating it. Eg:

const [departmentNames,setDepartmentNames] = React.useState([]);
let newArray = [];

Object.keys(departments).forEach((key)=>{
    console.log("department="+departments[key].name)
    newArray.push(departments[key].name)        
});
setDepartmentNames(newArray);

Upvotes: 1

Related Questions