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.
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!
Simply use forceUpdate method to force React to Re-Render the 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.
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}`} /> ) }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With