2

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>

1
  • Welcome to Stack Overflow. Do you mean that you want to remove the user from the state? Commented Dec 30, 2018 at 22:54

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you! Getting this error: TypeError: this.state.users.map is not a function
You're welcome :) are you seeing this error immediately, or after clicking the Remove button?
After clicking the Remove Button
From the documentation it appears that delete(jsonplaceholder.typicode.com/users/${id}) does not return a list of users (as your code expects) - one option is to issue the "delete" request and follow that by a "list query". Did you want me to update the code to show this?
Yes please, that would be really nice!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.