Home > Software design >  How can I delete data using react and axios?
How can I delete data using react and axios?

Time:10-04

I'm tryng to create a list using .map(), but when I try to console the user._id on my back-end, it shows all the ids, but I don't want it, i wanna use .map() to delete each post individually, using a button. Each post with name, age and e-mail got a button that I need to use to delete the current data.

Here's my code:

import React from "react"
import axios from "axios"
import { useState, useEffect } from "react"
import { Link } from "react-router-dom"

const deletePost = (userid) => {

    axios.post('http://localhost:3001/deleteUser', {_id: userid})

}

function userlist() {

    const [listOfUsers, setListOfUsers] = useState([])
    
    useEffect(() => {

        axios.get('http://localhost:3001/userlist').then((response) => {

            setListOfUsers(response.data)
        })

    })

    return (

        <div className="userlistdiv">

            {listOfUsers.map((user) => {

                return (

                    <div className="userdiv">
                        <h1>Id: {user._id}</h1>
                        <h1>Name: {user.name}</h1>
                        <h1>Age: {user.age}</h1>
                        <h1>E-mail: {user.email}</h1>
                        <button onClick={deletePost(user._id)}>Delete</button>
                        <hr></hr>
                    </div>
                )
            } )}

        </div>
    )
}

export default userlist;

And here's my code when I try to use console.log to see what is going on:

const express = require('express');
const app = express();
const PORT = 3001;
const mongo = require('./mongo')
const usersModel = require('./models/userschema')
const cors = require('cors')
app.use(express.json())
app.use(cors())


app.get('/userlist', (req, res) => {

    usersModel.users.find({}).then((result, err) => {
        if(err) {
            res.json(err)
        }

        else {
            res.json(result)
        }
    })
})

app.post('/deleteUser', (req, res) => {

    console.log(req.body._id)
    usersModel.users.findOneAndDelete({_id: req.body._id})
    
  

})

app.post('/createUser', (req, res) => {


    const newUser = usersModel.users({name: req.body.name, age: req.body.age, email: req.body.email})
    newUser.save()
})

app.listen(PORT, () => {

    console.log('Servidor rodando na porta '   PORT);


})

I'm using this "console.log" in the back-end to see what's the result that my front is sending to the back-end, and it shows all the _id's, i think it's because i'm using .map(), so, how can I resolve this, to return only the _id of the post that I want to delete using a button?

CodePudding user response:

<button onClick={() => deletePost(user._id)}>Delete</button>

This should be the correct way to call a function on button click

CodePudding user response:

This code belows immediately calls deletePost(user._id) when the function renders.

<button onClick={deletePost(user._id)}>Delete</button>

What you want to do is pass a callback function to onClick to execute:

<button onClick={() => deletePost(user._id)}>Delete</button>

This way you are allowing the button to call the function when the button is clicked.

  • Related