I have a simple app for CRUD operations, now I can delete, edit, and display data, but I want to add new items to a list of users fetched from API(JSON server fake API) using react and redux.
Now when I click add user and save the data only id is sent but other data are not sent.
here is a live demo: Redux live demo with source code sandbox .
Here is my form, AddUserForm.js
import React, { useState } from 'react'
import {useDispatch} from 'react-redux'
import { addNewUser } from '../redux/acitons/users/Users';
function AddUserForm({users}) {
const dispatch = useDispatch();
const [newUserName, setNewUserName] = useState('');
const handleSubmit = (e) =>{
e.preventDefault();
const usersList = users;
const newUserId = usersList[usersList.length - 1].id + 1;
console.log("your name", newUserName);
console.log("your id", newUserId)
dispatch(addNewUser({
...users,
id: newUserId,
name: newUserName,
}));
}
const handleCancel = () => {};
return (
<tr>
<td>{newUserName.id}</td>
<td>
<input
value={newUserName}
name="name"
onChange={e => setNewUserName(e.target.value)}
/>
</td>
<td>
<button type="button" className="btn outline" onClick={handleCancel}>
<i className="material-icons">Cancel</i>
</button>
<button
type="button"
className="btn btn-success btn-link"
onClick={handleSubmit}
>
<i className="material-icons">save</i>
</button>
</td>
</tr>
);
}
export default AddUserForm
and I call like this in parent components with the on click button.
{adding && <>
<AddUserForm addNewUser={addNewUser} users={userData.users} />
</>}
Here is a button in the parent components.
<button
type="button"
className="btn btn-success btn-link btn-add"
onClick={() => setAdding(true)}
>
<i className="material-icons">Add user</i>
</button>
What is wrong with my code? any help or suggestions will be appreciated.
