My react app allows the user to upload photos from their system and facebook (yet to be implemented). After uploading from the system, the URL of the displayed images are object URLs. Upon clicking Save, presigned URLs are requested from the server for each image. The presigned URLs are split to get only the URL portion (uptil .png or .jpg). Then the image source URLs are changed to the presigned URLs. The expectation is that the image refreshes by loading the image from the new image source. But it does not. However, if I right-click on select load image, the image loads. I tried things like cachebreaker, putting the image rendering code in a react component, using onError fallback, unique keys on images. Doesn't work. Can anyone let me know a workaround. Code is as below. Here is a quick anatomy of my code:
useEffect - displays the save button only when there is an image added to the image array. Currently local images are added. In the future images will be added from various sources like AWS S3, instagram, facebook etc
inputFilePickerFunc - Currently this function validates the dimensions of images picked from the local system. In the future this function will validate dimensions of images loaded from external APIs. This function after validating the dimensions to ensure that the images are appropriately sized, adds the images to the image array. The local URLs are converted to Object URLs for the image sources.
setImgProfilePic - Set an image as profile pic.
deleteItem - Deletes an image from the DOM.
savePics - Calculates the number of images to save to S3. Gets those many presigned URLs. Saves the images to S3. When S3 responds that the upload was a success, splits the presigned URLs to get only the part that downloads the image, and assigns this split part as the new source of the images.
So the issue is that in savePics, the images don't refresh although their sources have changed. I have to manually ask the browser to refresh the page, by right-clicking and selecting "load image".
photopicker.js
import Box from '@mui/material/Box'
import * as React from 'react';
import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";
import '../../css/styles.css'
import Typography from '@mui/material/Typography';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faRectangleXmark } from "@fortawesome/free-solid-svg-icons";
import { faTrashCan } from "@fortawesome/free-solid-svg-icons";
import { faComputer } from "@fortawesome/free-solid-svg-icons";
import FacebookIcon from '@mui/icons-material/Facebook';
import Icon from '@mui/material/Icon';
import { useRef } from 'react';
import Button from '@mui/material/Button';
// import { Provider } from 'react-redux';
import { store } from '../appstate/store'
// import { useSelector, useDispatch } from 'react-redux'
// import { picArrayAdd, picArrayDel } from '../appstate/photopickerslice';
import axios from 'axios';
import Tooltip from '@mui/material/Tooltip';
export default function PhotoPicker() {
const inputRef = useRef();
const openFileDialog = (e) => {
inputRef.current.value = null;
inputRef.current.click()
}
// const initialImageArrayState = [];
const [presignedURL, setPresignedURL] = useState('');
const [imageArray, setImageArray] = useState([]);
const [displaySaveCancelButton, setDisplaySaveCancelButton] = useState("none");
const [profilePic, setProfilePic] = useState('');
useEffect(() => {
imageArray.length !== 0 ? setDisplaySaveCancelButton("") : setDisplaySaveCancelButton("none")
})
const inputFilePickerFunc = (e) => {
// console.log(e.target.files);
var file = e.target.files;
var k = Object.keys(file);
var objStore = [];
k.forEach(
(key) => {
objStore.push(file[k[key]]);
}
);
//Check if file is image
let pattern = /image/
objStore.forEach((index) => {
let text = index.type;
/* console.log(text); */
let result = text.match(pattern);
if (result == null) {
console.log('invalid file');
objStore.splice(index, 1)
}
})
//Check image size
objStore.forEach((index) => {
let imageSize = index.size;
/* console.log(text); */
if (imageSize > 15728640) {
console.log('file ' + index + ' image is bigger than 15 MB size limit.');
objStore.splice(index, 1)
}
})
//check image dimensions
objStore.forEach(
(item) => {
var im = new Image();
im.src = URL.createObjectURL(item);
im.onload = function () {
if (im.width < 400 || im.height < 500) {
objStore.splice(item, 1);
console.log('dimensions should be minimum 400 x 500 of image ' + item.name)
}
else {
console.log(imageArray);
setImageArray(prevState => {
return [...prevState, { "imagesource": im.src, "profilepic": "no", "file": item, "inS3": "no" }]
}
)
}
}
console.log(imageArray)
}
)
}
const setImgProfilePic = (e) => {
setProfilePic(e.currentTarget.id);
let imageArrayDump = [...imageArray];
for (let i = 0; i < imageArrayDump.length; i++) {
if (imageArrayDump[i].profilepic == "yes") {
imageArrayDump[i].profilepic = "no";
break;
}
}
for (let k = 0; k < imageArrayDump.length; k++) {
if (imageArrayDump[k].imagesource == e.currentTarget.id) {
imageArrayDump[k].profilepic = "yes";
setImageArray([...imageArrayDump]);
break;
}
}
}
function deleteItem(e, item) {
e.stopPropagation();
let indexofItemtoBeDeleted;
let dupArr = imageArray.slice();
for (let i = 0; i < dupArr.length; i++) {
if (dupArr[i].imagesource == item) {
indexofItemtoBeDeleted = i;
break;
}
}
dupArr.splice(indexofItemtoBeDeleted, 1);
setImageArray([...dupArr]);
}
function savePics() {
//check in the image array the number of items with inS3 = no, and send this number to API
let presignedURLsRequired = [];
for (let i = 0; i < imageArray.length; i++) {
if (imageArray[i].inS3 == "no") {
presignedURLsRequired.push(imageArray[i].file.type);
}
}
axios.post('/presignedUploadURL', {
"numberOfPresignedURLsRequired": presignedURLsRequired
}).then(
(res) => {
let imageArrayDump = [...imageArray];
for (let i = 0; i < imageArrayDump.length; i++) {
for (let k = 0; k < res.data.length; k++) {
if (imageArrayDump[i].file.type == res.data[k].imageType) {
imageArrayDump[i].presignedURL = res.data[k].presignedURL;
res.data.splice(k, 1);
}
}
}
console.log(imageArrayDump);
for (let j = 0; j < imageArrayDump.length; j++) {
axios.put(imageArrayDump[j].presignedURL, imageArrayDump[j].file)
.then(
(res) => {
if (res.status == 200) {
imageArrayDump[j].inS3 = "yes";
}
}
)
.catch(res => console.log(res));
}
for(let l = 0; l < imageArrayDump.length; l++){
let newImageSource = imageArrayDump[l].presignedURL.split('?')[0];
imageArrayDump[l].imagesource = newImageSource;
delete imageArrayDump[l].presignedURL;
}
setImageArray([...imageArrayDump]);
}
).catch(err => console.log(err));
}
return (
<Box sx={{ border: 1, display: 'flex', flexWrap: 'wrap', width: '50%', margin: 'auto', minWidth: '570px' }}>
<Box sx={{ display: 'flex', border: 1, borderColor: 'red', width: '100%', flexWrap: 'nowrap' }}>
<Typography sx={{ border: 1, width: '100%', minHeight: '30px', textAlign: "center" }}>
Upload pictures
</Typography>
<Icon onClick={() => alert("hi")} sx={{ border: 1, cursor: "pointer" }}>
<FontAwesomeIcon icon={faRectangleXmark} />
</Icon>
</Box>
<Box sx={{ border: 1, width: '49.5%', minHeight: '50px', textAlign: "center", cursor: "pointer" }} onClick={openFileDialog}><input ref={inputRef} type="file" multiple onChange={inputFilePickerFunc} style={{ display: 'none' }}></input><Typography>Computer</Typography><Icon><FontAwesomeIcon icon={faComputer} /></Icon></Box>
<Box sx={{ border: 1, width: '49.5%', minHeight: '50px', textAlign: "center" }}><Typography>Facebook</Typography><Icon sx={{ color: 'blue' }}>FacebookIcon</Icon></Box>
{
imageArray.length !== 0 &&
(
imageArray.map(
(item, index) => {
let itemImgSrc = item.imagesource
return (
<Tooltip key={`${itemImgSrc}1`} title={profilePic == item.imagesource ? "" : "Set as profile pic"}>
<Box key={`${itemImgSrc}2`} id={item.imagesource} style={{ border: profilePic == item.imagesource ? "2px solid red" : "0px" }} onClick={setImgProfilePic} sx={{ width: '49.5%', height: "150px", position: 'relative', cursor: "pointer" }}><Icon id="icon" key={`${itemImgSrc}3`} sx={{ position: 'absolute', right: '0px', cursor: "pointer", color: 'red' }} onClick={(e) => { deleteItem(e, item.imagesource) }}><FontAwesomeIcon icon={faTrashCan} /></Icon><img src={item.imagesource} id={itemImgSrc} index={index} key={`${itemImgSrc}4`} style={{ width: '100%', height: '100%', objectFit: 'contain' }}></img></Box>
</Tooltip>
)
}
)
)
}
<Box sx={{ width: '100%', textAlign: "center", display: displaySaveCancelButton }}><Button variant="contained" sx={{ m: 2 }} onClick={savePics}>Save</Button></Box>
</Box>
)
}
I used document.location.reload() and it worked without refreshing the page. The links were established.