Reputation: 5556
I am learning react-redux, so I am creating a CRUD app for users using JSON placeholder API, now I am able to display data, delete and edit, but I have a problem with adding data.
Here is a live demo in the sandbox : redux live demo
Now when I click add user button I get the following error.
Cannot read property 'editing' of undefined.
Here is my form component to add a user.
import React, { useState } from 'react'
import {useDispatch} from 'react-redux'
import {addUser, addNewUser } from './redux/acitons/users/Users';
function AddUserForm({ user }) {
const dispatch = useDispatch();
const [name, setName ] = useState(user.name);
const handleSubmit = () =>{
console.log(name)
dispatch(addNewUser( {
...user, name
}));
}
const handleCancel = () => {
console.log(user.id);
dispatch(addUser(user.id))
}
return (
<tr>
<td>{user.id}</td>
<td>
<input
defaultValue={user.name}
onChange={e => setName(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
What do I need to do to solve the problem?, any help or suggestions will be appreciated, the live demo can be found here in the sandboxredux demo
Upvotes: 2
Views: 249
Reputation: 2086
Looking at your code - it seems like your app is breaking since you are not passing any user-payload object to theaddUser
dispatch call(on User.js
line 64).
Here's a possible way to solve this:
Passing a new-user payload object with an id 1 higher than the previous user on the list) and then dispatch an editUser
for that new id.
const addNewUser = () => {
const usersList = userData.users;
const newUserId = usersList[usersList.length - 1].id + 1;
addUser({
id: newUserId
});
editUser(newUserId);
};
This is a very simplified solution (for example - a better approach would be to give a unique id to each user and index the list on the client not based on the server ids) - but it should give you an idea of how to take this forward.
Upvotes: 1
Reputation: 151
Well first of all, to temporary handle compile errors put question marks on user?.editing and other places where you use user.id or other parameters. Other thing, I can see that you are using id for editing and deleting so you should also set id property in your userForm
Upvotes: 0