I am trying to reset the state for an object stored in my users
array on click with handleDelete
after I remove from the database. However, my state is not changing. I am able to log the current user with console.log('found: ' + this.state.users[i])
. Basically, I have a table populated from my API and am trying to remove the row for the state without refreshing the page, but the state is not updating.
The constructor where my initial state is stored:
constructor(props) {
super(props);
this.state = {
users: []
}
this.handleDelete = this.handleDelete.bind(this);
};
Grabbing the API on mount:
componentDidMount() {
fetch('/myAPI')
.then(res => res.json())
.then(users => this.setState({ users }));
}
Mapping over data stored in state from fetch
render() {
return (
<tbody>
{this.state.users.map(user =>
<tr key={user.uniqueid}>
<td>{user.name}</td>
<td>{user.versions}</td>
<td>{user.type}</td>
<td>{user.hours}</td>
<td>{user.refresh}</td>
<td>{user.uniqueid}</td>
<td>{user.date}</td>
<td><Button onClick={this.handleDelete} data-id={user.uniqueid}><FaTrashO /></Button></td>
</tr>
)}
</tbody>
);
}
delete handler where I am TRYING to reset state for :
handleDelete(e) {
let dataId = e.target.getAttribute('data-id');
axios({
method: 'delete',
responseType: 'json',
url: '/myAPI',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Methods': "GET,HEAD,OPTIONS,POST,PUT"
},
data: { _id: dataId }
})
.then((response) => {
console.log(dataId + ' deleted with axios')
for (let i = 0; i < this.state.users.length; i++){
if (dataId === this.state.users[i]._id) {
let currentObj = this.state.users[i];
console.log('found: ' + this.state.users[i])
this.setState((prevState) => {
currentObj._id = ''
currentObj.date = '',
currentObj.hours = '',
currentObj.name = '',
currentObj.refresh = '',
currentObj.type = '',
currentObj.uniqueid = '',
currentObj.versions = ''
});
}
}
})
.catch((err) => {
throw err;
})
}
Example of what im calling from my API:
[
{
_id: "XJAbmHCX",
name: "an_example_2",
type: "B",
versions: "10",
hours: "10",
refresh: "Yes",
uniqueid: "XJAbmHCX",
date: "2018/01/08",
__v: 0
},
{
_id: "TOoIi7xS",
name: "test",
type: "A",
versions: "10",
hours: "10",
refresh: "Yes",
uniqueid: "TOoIi7xS",
date: "2018/01/09",
__v: 0
},
{
_id: "oeaigjesroigj",
name: "an_example_2_1",
type: "B",
versions: "10",
hours: "10",
refresh: "Yes",
uniqueid: "oeaigjesroigj",
date: "2018/01/08",
__v: 0
}
]
In the for loop of handleDelete
, I simply sliced the user adn returned every object without the current ID to the state
for (let i = 0; i < this.state.users.length; i++){
if (dataId === this.state.users[i]._id) {
let users = this.state.users.slice();
users = users.filter(u => { return u._id !== dataId; });
this.setState({ users: users });
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.