Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force React to reload an image file?

Tags:

reactjs

My React app allows users to upload profile images. This is done by uploading the image to an Amazon S3 bucket and storing the path to the image in my database, along with the date and time the image was uploaded. The filename of the image is set to the user's ID.

Im having a problem when a user uploads a new image. As the image path is the same React doesn't know anything has changed, meaning I have to refresh the page to see the change.

As I have a date field I can use componentWillReceiveProps to know when a new image has been uploaded. The following console.log does fire at the correct time:

componentWillReceiveProps(nextProps) {     if (this.state.picDate.getTime() !== nextProps.user.pic.date.getTime()) {         console.log('image date has changed');         // this.forceUpdate();     } } 

Can I use this to re-render the image? I tried this.forceUpdate() but it doesn't work.

like image 399
Evanss Avatar asked Dec 21 '17 10:12

Evanss


People also ask

How do you force reload in React?

If set to true, the browser will do a complete page refresh from the server and not from the cached version of the page. import React from 'react'; function App() { function refreshPage() { window. location. reload(false); } return ( <div> <button onClick={refreshPage}>Click to reload!

How do you're-render an image in React?

Simply use forceUpdate method to force React to Re-Render the component.

How do I force refresh a component?

Forcing an update on a React class component In any user or system event, you can call the method this. forceUpdate() , which will cause render() to be called on the component, skipping shouldComponentUpdate() , and thus, forcing React to re-evaluate the Virtual DOM and DOM state.


2 Answers

I think that's because of the browser cache. try adding some hash like date.now() after image URL changes. for example:

setState({    imageSrc: '...',    imageHash: Date.now() }) 

and in render:

render(){   return(       <img src={`${imageSrc}?${imageHash}`} />   ) } 
like image 50
Emad Emami Avatar answered Sep 18 '22 08:09

Emad Emami


I was having this issue with a local image. The image was being modified, but the URL was staying the same.

The trick was just to add a key property to the image that changed whenever the image changed. For instance:

<Image key={Date.now()} source={{uri: <your local uri>}/> 

Source: this GitHub comment

like image 22
Eric Wiener Avatar answered Sep 21 '22 08:09

Eric Wiener