简体   繁体   中英

Delete data from API with Axios and ReactJS

I am fetching data from the jsonplaceholder API into my state. How can I remove the data with the deleteContact() method? My greatest struggle is how to get the deleteContact() method right.

Is this approach wrong?

 class RemoveFromAPI extends Component { state = { users: [] } componentDidMount() { axios.get(`https://jsonplaceholder.typicode.com/users`) .then(res => { const users = res.data; this.setState({ users }); }) } deleteContact () { axios.delete(`https://jsonplaceholder.typicode.com/users/${id}`); .then(res => { const users = res.data; this.setState({ users }); }) } render() { const {users} = this.state return ( <div> <ul> { this.state.users.map(user => <li>{user.name}</li>)} </ul> <button onClick={deleteContact} > Remove </button> </div> ); } } RemoveFromAPI.propTypes = {}; export default RemoveFromAPI; 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> 

A few things to revise here - first, it seems you need to pass the user.id to the deleteContact() function, given that your axios request requires the user id as part of the request URL. This typically means moving the "Remove" button into the map() render callback so that each user id can be passed through the buttons click handler:

render() {

    const {users} = this.state

    return (<div>
            <ul>
            { 
              this.state.users.map(user => (
              <li>{user.name}
                  <button onClick={ () => this.deleteContact(user.id) } >Remove</button>
              </li>))
            }
            </ul>
        </div>);
}

Also, note the use of the "arrow function" passed on onClick :

() => this.deleteContact(user.id) 

Arrow functions provide a convenient way to call a class methods that are bound to the current component instance. This is important to ensure methods like setState() work as expected from inside the class method being called.

Finally, the deleteContact() method itself needs some minor revisions. Ensure the id parameter is declared as a function argument and also remove the ; following your axios.delete() to avoid a syntax error, like so:

deleteContact (id) { // <-- declare id parameter
    axios.delete(`https://jsonplaceholder.typicode.com/users/${id}`) // <-- remove ;
    .then(res => {
        const users = res.data;
        this.setState({ users });
    })
}

Hope that helps!

Update

Another note; your code is expecting the API at https://jsonplaceholder.typicode.com/ to return list of items after a DELETE request according to the documentation this doesnt seem to be the API's behavior. One way to address this would be to update deleteContact() to first issue the DELETE request, followed by a GET request like so:

deleteContact (id) {

    // Issue DELETE request
    axios.delete(`https://jsonplaceholder.typicode.com/users/${id}`)
    .then(() => {

        // Issue GET request after item deleted to get updated list
        // that excludes user of id
        return axios.get(`https://jsonplaceholder.typicode.com/users`)
    })
    .then(res => {

        // Update users in state as per-usual
        const users = res.data;
        this.setState({ users });
    })
}

Note also, this placeholder API does not actually remove data from the server which will mean the delete operation will appear to have no effect.

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