React onClick with axios is refresh after sent

1.1k views Asked by At

in onClick, I call the function and use preventDefault() but the web page is refreshed. I'm not sure if it about's axios because when it done to fetching the web page is refreshes immediately.

function submit(event){
    event.preventDefault();
    
    const formData = new FormData();
    formData.append("name", name);

    axios({
        method: "POST",
        url: "http://localhost:5000/insert-data",
        headers: {"Content-Type": "multipart/form-data"},
        data: formData,
        onUploadProgress: (e)=>{
            if(e.lengthComputable){
                console.log(((e.loaded * 100 / e.total)+"").split(".")[0])
            }
        }
    }).then(res=>{
        console.log(res.data);
    })

form

<input type="text" placeholder="name" onChange={e=>setName(e.target.value)} /> <br />
<input type="file" onChange={e=>setVideo(e.target.files[0])} /> <br />
<button type="button" onClick={submit}>Insert Data</button>
2

There are 2 answers

1
Arihant Jain On
const submit=(event)=>{
    event.preventDefault();
    
    const formData = new FormData();
    formData.append("name", name);

    axios({
        method: "POST",
        url: "http://localhost:5000/insert-data",
        headers: {"Content-Type": "multipart/form-data"},
        data: formData,
        onUploadProgress: (e)=>{
            if(e.lengthComputable){
                console.log(((e.loaded * 100 / e.total)+"").split(".")[0])
            }
        }
    }).then(res=>{
        console.log(res.data);
    })

Try if adding a form tag solves this issue

<form onSubmit={submit}>
    <input type="text" placeholder="name" onChange={e=>setName(e.target.value)} /> <br />
    <input type="file" onChange={e=>setVideo(e.target.files[0])} /> <br />
    <button type="submit">Insert Data</button>
</form>
0
Loga Thrim On

I have an answer to my question, It because when I submit files to api the filename is already exists in my upload folder, so I solved it with a unique filename.

But I don't know why because response from api is same, it not error

this is my api (Nodejs)

req.files.video.mv(path.join(__dirname + "/../public/videos/" + req.files.video.name), err=>{
        if(err) throw err;

        dbcon.collection("user").update({_id: ObjectId(id)}, {$push: {level: {
            name, video: req.files.video.name
        }}}, (err, doc)=>{
            if(err) throw err;
            res.json({status: "success"})
        })
    })