I think this question is related to how React apps are written in general.
- For user sessions I use -
NextAuth.js
- All user data (incl profile image) from NextAuth is stored on
Supabase (PostgreSQL)
How to show user's new profile image across everywhere that uses it (without page refresh)?
Let's say:
- I update user's profile image in a
Settings
page - The updated image is showing fine on
Settings
- But the old image is still on the navbar (
Navbar
component), unless I refresh the page
Settings
page:
const Settings = (props: any) => {
const { data: session } = useSession()
const user = session?.user
const [file, setFile] = useState<File | null>(null)
const [image, setImage] = useState<string | null>(null)
let uploadHandler = async (file: File) => {
const formData: any = new FormData()
formData.append('file', file)
try{
// assume I update the user (and their profile image) in the database here
// and receive a url of the uploaded image here
const { data } = await axios.post(......)
setImage(data?.url)
}
catch (error){
}
}
useEffect(() => {
(async () => {
if (file){
await uploadHandler(file)
}
})();
}, [file])
useEffect(() => {
setImage(user?.image!)
}, [user])
return (
<>
<Avatar src={image} />
<FileButton onChange={setFile} accept="image/png,image/jpeg">
{(props) => <Button {...props}>Upload photo</Button>}
</FileButton>
</>
)
}
export default Settings
Navbar
component:
export function UserAvatar(props: any) {
const { data: session } = useSession()
const user = session?.user
return (
<>
...
<Avatar src={user?.image!} />
...
</>
);
}