I'm using React Query to grab all of the uploaded CDN URLs (photos) from the DB and successfully displaying them upon the user navigating to the Gallery.js component.
However, every time a user tries to upload a photo - they'd need to refresh the page in order for their uploaded photo to be displayed.
Below's one of my many failed attempts as I've hit a wall.
How can I make it so that the photo they've uploaded gets displayed upon successful upload?
Gallery.js
// Newly uploaded photo
const [newlyUploadedUrl, setNewlyUploadedUrl] = useState("");
const [newlyUploadedFlag, setNewlyUploadedFlag] = useState(false);
const fileUpload = () => {
const url = 'http://localhost/api/file-upload';
let formData = new FormData();
let imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
const headers = {
"Accept": 'application/json',
"Authorization": `Bearer ${authToken}`
}
axios.post(url, formData, {headers})
.then(resp => {
let photoUrl = resp.data.url;
setNewlyUploadedFlag(true);
setNewlyUploadedUrl(photoUrl);
}).catch(error => {
console.log(error);
});
}
async function fetchUploads() {
const headers = {
"Accept": 'application/json',
"Authorization": `Bearer ${authToken}`
};
const {data} = await axios.get('http://localhost/api/get-user-uploads-data', {headers});
return data;
}
const { data } = useQuery('uploads', fetchUploads);
<div className="main">
<ul className="cards">
{
data.map((photos) => {
return(
<>
<Grid
newlyUploadedFlag={newlyUploadedFlag}
newlyUploadedUrl={newlyUploadedUrl}
src={photos.url}
/>
</>
);
})
}
</ul>
</div>
Here's Grid.js:
const Grid = (props) => {
return (
<>
<img src={!props.newlyUploadedFlag ? props.src : props.newlyUploadedUrl} alt="Photo" className="gallery-img" />
<span style={{display: 'none'}}>{props.newlyUploadedFlag}</span>
<span style={{display: 'none'}}>{props.newlyUploadedUrl}</span>
</>
);
}