I just made a table to display customers emails and added functions to remove or add new emails.
but for add function, I saved new email into state(users
). but it's not showing in email table list. remove function is working great! could you help me to fix this issue?
Just attached my code
import React, {useState} from 'react';
const Admin: NextPage = () => {
const [users, setUsers] = useState([
{ email: "[email protected]" },
{ email: "[email protected]"},
]);
const [email, setEmail] = useState('');
const removeUser = rowEmail => {
const updatedArray = users.filter((row) => row.email !== rowEmail);
setUsers(updatedArray);
}
const addUser = () => {
console.log(email);
const lists = users;
lists.push({'email' : email});
setUsers(lists);
}
return (
<>
<div className="user-user">
<input type="email" onChange={event => setEmail(event.target.value)} />
<span onClick={() => addUser()}>Add User</span>
</div>
<div className="user-list">
<table>
<thead>
<tr>
<th>Users</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{users.map((val, key) => {
return (
<tr key={key}>
<td>{val.email}</td>
<td><span onClick={() => removeUser(val.email)}>Remove</span></td>
</tr>
)
})}
</tbody>
</table>
</div>
</>
);
}
export default Admin;
CodePudding user response:
The line const lists = users;
does not create a new array. It just creates a new variable that points to the same array. So the lists.push({'email' : email});
will mutate the state, but in a way that react will not get notice of it.
use
const lists = [...users];