Home > Blockchain >  React - costumers.map is not a function
React - costumers.map is not a function

Time:03-02

My problem is: when I try to change the inputs it throw costumers.map is not a function. I'd like to change value and update datas in db.

//hook for fetching
    const [costumers, setCostumers] = useState([]);

    //fetching data from db by id
    useEffect(() => {
        Axios.get(`http://localhost:3001/profile/${id}`)
            .then((response) => {
                if (response) {
                    setCostumers(response.data);
                }
                else {
                    alert('Error')
                }
            })
    }, [])

and here is how i try to map, otherwise it seems like, onChange mehtod couse the problem.

    {costumers.map(costumer =>
        <div key={costumer.id}>
            <div className="containerProfile">
                <div className="leftInputProfile">
                    <p>Full Name</p>
                    <input type="text" name='Fullname' placeholder={!costumer.Fullname && "Adja meg az adatot"}
                        onChange={(e) => {
                            setCostumers({ ...costumers, [e.target.name]: e.target.value });
                        }}
                    />
                </div>
            </div>
        </div>

I know that, .map() method have to get an array, but i dont know the solution here :(

response.data: enter image description here

CodePudding user response:

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

setCostumers({ ...costumers, [e.target.name]: e.target.value });

You have to call it with brackets [] instead of curly braces {}:

setCostumers([ ...costumers, yourNewCustomer ]);

CodePudding user response:

You're setting the state to become an object:

setCostumers({ ...costumers, [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.

  • Related