简体   繁体   中英

After axios call, how should I update the front-end? [I have 2 ways]

I have an array of todos. When I delete one of them, I succesfully delete it also from the database with DELETE call. However, I am not sure how to update the front-end. First way is changing the state by deleting the related todo.

onDelete(todo) {
    axios.delete('api/todos/' + todo.id).then(res => {
        var array = [...this.state.todos]; // make a separate copy of the array
        var index = array.indexOf(todo)
        array.splice(index, 1);
        this.setState({todos: array}); // other state elemenets other than todos will not be affected
    });
}

Other way is, making a new axios GET request to get all the todos from the database. (this will be an axios request inside an axios request)

onDelete(todo) {
    axios.delete('api/todos/' + todo.id).then(res => {
        // make an axios get request on api/todos
        // then, set state with data in response.
    });
}

Hence, which one is the better approach?

The best approach would be the second one, to call a get request once more. So that no matter what the change database has undergone, the UI will be an exact replica of the data from db instead of manually changing(deleting in this case) the list from UI. However there will be the delay of api response for UI updation in this case.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM