Search code examples
angularsupabase

The image is not re-loaded from Supabase


I have such easy function in my Angular app:

downloadCategoryPhotoFromSupabase(path: string) {
    this.categoryPhoto = this.supabase.storage
      .from('categories')
      .getPublicUrl(path).data.publicUrl;
  }

It is executed every time information about this category is loaded (or updated) into my category unit component. At the same time, the link in the background-image and the link of the uploaded image to the Network in the browser looks like this: ###.supabase.co/storage/v1/object/public/categories/0.4668829289505223.png. However, if I create a category, or update an existing category photo, the image url is updated (and if you click on it, there will be a working image), but the image element itself loses any image source at all (although the background-image) is there and is simply displayed with the background-color of this element.

The updated link has the same kind of path as above, however, it tries to load another one in the Network: ###.supabase.co/storage/v1/object/categories/0.4668829289505223.png

When trying to follow such a link without 'public' I see the following: {"statusCode":"400","error":"Error","message":"headers must have required property 'authorization'"} After the page is reloaded, the image loads correctly. Maybe someone have an answer?


Solution

  • The issue with the image element losing its source after updating the category photo is the way the image URL is being constructed and the timing of the update

    Your <img> element is trying to load old url, but it fails because image has been moved to new url

    This will ensure that the categoryPhoto property is updated with the new public URL only after it is available, preventing the <img> element from losing its source.

    downloadCategoryPhotoFromSupabase(path: string) {
      this.supabase.storage
        .from('categories')
        .getPublicUrl(path)
        .subscribe((data) => {
          this.categoryPhoto = data.data.publicUrl;
        });
    }