How to Stop component to refresh after axios post in react. After uploading image from formData

Viewed 2992

I am building a blog builder where i need to upload the image as image is selected on onChange event and that url of uploaded image need to be updated in state.

After post request for image upload . Component gets refreshed automatically and selected file and state is also refreshed.

what to do to stop component from refreshing and the setState to update the correct url of image..

handleChange = async (event) =>
{
    event.preventDefault();
    if(event.target.name == 'file')
    {


        var x=event.target.files[0]
        var y= event.target.name
        let formData = new FormData();
        formData.append('file',x)
        const response = await axios.post('http://localhost:8009/post/image',formData,{
           headers: {
             'Content-Type': 'multipart/form-data'
          }
        })
        let {data} = await response
        console.log(data)
        let file1 = data.name
        this.setState({
            content:{
                key:uuid(),
                name:y,
                file:file1,
                content:URL.createObjectURL(x)
            }
        })

   }
}

The form for Image is as :

<input type="file" name="file" className="form-control-file"  onChange={this.handleChange} required/>

Backend on node :

router.post('/image',(req,res)=>
{
    console.log(req)

    let file = req.files.file;
    filename = Date.now() + '-' + file.name;

    file.mv(`./client/public/uploads/${filename}`, (err)=>{

        if(err) throw err;

    });
    console.log(`/uploads/${filename}`);
    res.json({name:`/uploads/${filename}`})
})
1 Answers

I see you're uploading to your local environment. I had a similar issue working with Vue, but then stumbled upon this answer by @fanfare pointing out that if you're using any kind of "hot/live refresh" (in Vue is called Hot Module Reload) and the file is being uploaded in any of the folders the server monitors for changes, then the new file being saved could be the cause of the refresh.

In my case saving the file outside of the monitored folder solved the issue.

Related