'React - customers.map is not a function
My problem is: when I try to change the inputs it throw customers.map is not a function. I'd like to change value and update data in the database.
//hook for fetching
const [customers, setCustomers] = useState([]);
//fetching data from db by id
useEffect(() => {
Axios.get(`http://localhost:3001/profile/${id}`)
.then((response) => {
if (response) {
setCustomers(response.data);
}
else {
alert('Error')
}
})
}, [])
And here is how I try to map, otherwise it seems like, onChange method causes the problem.
{customers.map(customer =>
<div key={customer.id}>
<div className="containerProfile">
<div className="leftInputProfile">
<p>Full Name</p>
<input type="text" name='Fullname' placeholder={!customer.Fullname && "Adja meg az adatot"}
onChange={(e) => {
setCustomers({ ...customers, [e.target.name]: e.target.value });
}}
/>
</div>
</div>
</div>
I know that, .map() method have to get an array, but I don't know the solution here :(
response.data:
Solution 1:[1]
You're setting the state to become an object:
setCustomers({ ...customers, [e.target.name]: e.target.value });
If you want to update a specific customer you could write a separate handler such as:
const updateCustomer = (customerId) => (event) => {
const index = customers.findIndex((customer) => customer.id === customerId);
const nextCustomers = customers.splice(index, 1, {
...customers[index],
[event.target.name]: event.target.value,
});
setCustomers(nextCustomers);
}
You have to find the object to update, update it and replace it in the current state.
Your input should have at least <input name='Fullname' onChange={updateCustomer(customer.id)} value={customer.Fullname} />
You have to assign the value property too, as you're making it a controlled component with your input element.
Solution 2:[2]
I think your problem is in your onChange event you are setting your customers to an object {} which does not have the .map function by calling
setCustomers({ ...customers, [e.target.name]: e.target.value });
You have to call it with brackets [] instead of curly braces {}:
setCustomers([ ...customers, yourNewCustomer ]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | marc_s |
| Solution 2 | marc_s |

