简体   繁体   中英

How to update value in an object in an array using useState?

I want to update David and Brian's age to 25 using useState but I encounter an error:

TypeError: employees.map is not a function.

Can anyone suggest what should I do?

import React, { useState, useEffect } from 'react';

function App() {

    const [employees, setEmployees] = useState([]);

    useEffect(() => {
        setEmployees([
            { name: 'David', age: 40 },
            { name: 'Brian', age: 35 }
        ]);
    }, []);

    employees.map((value) => {
        setEmployees({ ...employees, age: 25 });
    });

    console.log(employees)
    
    return (
        <div>
            This is App component
        </div>
    );
};

export default App;

The main problem is you are using in setEmployees() an object {} instead of an [] . The function .map() can be used only on arrays. From the documentation:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

If you want to add a new element to that array you should use as:

setEmployees(prevState => [
   ...prevState,
   { name: 'New Guy', age: 25 }
]);

To update all the values you can use .map() as the following:

setEmployees(prevState => prevState.map(e => ({
   ...e,
   age: 25
});

See a live example below:

 const data = [ { name: 'David', age: 40 }, { name: 'Brian', age: 35 } ] const result = data.map(e => ({...e, age: 10})) console.log(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM