Axios.put ReactJS

Viewed 43

It's kinda working,but problem is it copies the file which is being updated and puts it in the end of page,All I'm trying to do display update on the item

Here what I'm trying to do

    submitEdit = (id, value) => {
    let {todos} = this.state
    todos.map((item => {
        if (item._id === id) {
            axios
                .put(`http://localhost:8080/edit/${id}`, {
                    todo: value,
                })
                .then((res) => {
                    this.setState({
                        todos:[...todos,{todo:value}]
                    })
                    console.log("res", res);
                })
                .catch((err) => {
                    console.log("err", err);
                });
        }
    }))
}

beside this everything is working fine

1 Answers

You need to update the state by using the index so that the todo element is updated and not copied and added to the end

You can use Array.prototype.slice with spread syntax to do that

todos.map(((item, i) => {
    if (item._id === id) {
        axios
            .put(`http://localhost:8080/edit/${id}`, {
                todo: value,
            })
            .then((res) => {
                this.setState({
                    todos:[...todos.slice(0, i),{todo:value}, ...todos.slice(i + 1)]
                })
                console.log("res", res);
            })
            .catch((err) => {
                console.log("err", err);
            });
    }
}))
Related