How to read data received by firestore get() - vue.js

I use vue and firestore.
I receive data through get().
onMounted(async () => {
const forminfo = db.collection('forms').doc(route.params.id)
const doc = await forminfo.get()
content.value = doc.data().content
url.value = doc.data().url
}
And use <p>{{content}} {{ url }} </p> in the template.
However, this method does not reflect the line break when writing and does not make url into an image.

For the image to display from the given url use
<img :src='url'/>
for the line break add <br> where you want to create a new line

Related

Display an image when Blob is returned from an API

I’m writing a Vue app which uses the Microsoft Graph API and SDK for initial authentication on the front end and then uses different aspects of the API throughout the app. Like displaying emails, OneDrive files, etc.
I’m using the profile photo from a users Microsoft account to display an avatar to other users. My issue is that when I call {graphApi}/me/photo/$value the result returned is a Blob. This is the endpoint provided in MS Graph.
I’ve read the MS Graph docs thoroughly, combed MDN & other sources and have not found a way to transform this result into a simple image in my markup.
Template markup:
<template>
<img :src="userPhoto" :alt="user.displayName" />
</template>
Setup function logic:
<script setup>
import { client } from "./foobar"
const userPhoto = ref();
async function getPhoto(){
const photo = await client.api("/me/photo/$value").get()
console.log(photo.value)
userPhoto.value = photo
};
</script>
Returned result:
{Blob, image:{id: default, size:48x48}}
So how do I decode or download the Blob properly to display an image in my Vue markup?? I’ve tried createObjectURL and FileReader() without any luck. I’m sure there is a simple solution but I am not finding it. Thanks for the help.
Explanation:
In below snippet as you can see I am passing the objectId of the Employee fetched from Graph previously.
Then making call for employee to get their Avatar/DP
The Graph Profile Photo endpoint returns binary Data of the photo.
Convert that binary data into data:image/png;base64,<readAsDataURL> URL e.g. data:image/png;base64,iVBORw0KGgoAAAANSU...
Use in <img src="dataUrl"/>
let imageUrl = (await request.get(GRAPH_CONFIG.GRAPH_DP_ENDPT + objectId + "/photos/48x48/\$value", { responseType: 'arraybuffer', validateStatus: (status) => status === 200 || status === 404 }))
if (imageUrl.status === 200) {
let reader = new FileReader()
let blob = new Blob([imageUrl.data], {type: 'image/jpeg'})
reader.onload = (event) => {
return event.target?.result.toString();
}
reader.readAsDataURL(blob)
}

Svelte: how to create a Blob from `writable store`?

How can I use a "writable store" to create a "blob"?
I am new to Svelte.
I am trying to code a simple markdown editor for visually impaired users. The content of the "textarea" is stored in a "writable store" for further use:
speech-synthesis
markdown-preview
the content of an existing text file is stored in it
save text to file
But saving the text content via download to a file does not work.
<script>
let blob = new Bob([$textStore], type:"text/plain");
let url = URL.createObjectURL(blob);
</script>
<button>
<a href={url} download="untitled.md" id="link">Download
</a>
</button>
An empty file is saved or it has the content "[object Object]", when I use curley brackets:
let blob = new Blob ([{$textStore}], {type: 'text/plain'});
File for testing:
// TextStore.js
import { writable } from "svelte/store";
export const textStore = writable('');
<!-- EditorTest.svelte -->
<script>
import { textStore } from "./TextStore.js";
let blob = new Blob ([{$textStore}], {type: 'text/plain'});
let url = URL.createObjectURL(blob);
</script>
<h1>Blob-Test</h1>
<textarea bind:value={$textStore} cols="20" rows="5"></textarea>
<hr>
<pre>{$textStore}</pre>
<br>
<button>
Save
</button>
Can someone help, thanks a lot already.
The main issue is, that the code is not reacting to the changes. The Blob is created once at the beginning, when the store is still empty. You could make it reactive using $:, but that is not a great idea, as it unnecessarily re-creates the Blob over and over.
I would recommend using a click handler on the button (the link inside it is invalid HTML anyway), and then creating the Blob there:
<button on:click={onDownload}>
Save
</button>
function onDownload() {
const blob = new Blob([$textStore], {type: 'text/plain'});
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.download = 'file.md';
link.href = url;
link.click();
URL.revokeObjectURL(url); // Object URLs should be revoked after use
}

Svelteki api fetch pages

In short, I want to fetch data from diferents pages from one API I've made.
The API is https://joao-back-ecommerce-prod.herokuapp.com/store/ and as you can see I've multiples endpoints.
With svelte i'm trying to go from page to page in one click with increment function.
exemple:
<script context="module">
export async function load({ fetch, page }) {
const id = page.params.id;
const res = await fetch(
`https://joao-back-ecommerce-prod.herokuapp.com/store/products/?page=${id}`
);
const products = await res.json();
console.log(products);
if (res.ok) {
return {
props: {
products: products.results
}
};
}
return {
status: res.status,
error: new Error('Could not fetch the results')
};
}
</script>
<script>
export let products;
export let id = 1;
const next = () => {
id++;
};
</script>
<ul>
{#each products as product}
<li>
{product.title} - {product.description}
<a href={product.id}>hlmlll</a>
</li>
{/each}
<button on:click={next}>Next</button>
</ul>
I want to go to next page when click on button next. I thought that with increment id + 1 it will be work, but, it doesn't.
In the browser when I change the page number it works.
Any help?
You are just changing a local variable, it does not affect the url.
What you would do is navigate to the next page by changing the url.
There are two ways to do this:
import { goto } from '$app/navigation';
const next = () => goto(`/product/${id+1}`); // change to get correct path for you
or, a better way is to actually just link to the next page instead:
Next
The second option is preferred because you are in fact navigating for which you should use a link (buttons are for actions), it will also work if the user has javascript disabled.
SvelteKit will not actually go to the server and load a new page, it will just fetch the data from the load function and update accordingly, the user will not notice they are on a different page, only the url changes.

Vuejs binding to img src only works on component rerender

I got a component that let's the user upload a profile picture with a preview before sending it off to cloudinary.
<template>
<div>
<div
class="image-input"
:style="{ 'background-image': `url(${person.personData.imagePreview})` } "
#click="chooseImage"
>
<span
v-if="!person.personData.imagePreview"
class="placeholder"
>
<i class="el-icon-plus avatar-uploader-icon"></i>
</span>
<input
type="file"
ref="fileInput"
#change="previewImage"
>
</div>
</div>
</template>
The methods to handle the preview:
chooseImage() {
this.$refs.fileInput.click()
},
previewImage(event) {
// Reference to the DOM input element
const input = event.target;
const files = input.files
console.log("File: ", input.files)
if (input.files && input.files[0]) {
this.person.personData.image = files[0];
const reader = new FileReader();
reader.onload = (e) => {
this.person.personData.imagePreview = e.target.result;
}
// Start the reader job - read file as a data url (base64 format)
reader.readAsDataURL(input.files[0]);
}
},
This works fine, except for when the user fetches a previous project from the DB. this.person.personData.imagePreview get's set to something like https://res.cloudinary.com/resumecloud/image/upload/.....id.jpg Then when the user wants to change his profile picture, he is able to select a new one from his local file system, and this.person.personData.imagePreview is read again as a data url with base64 format. But the preview doesn't work. Only when I change routes back and forth, the correct image selected by the user is displayed.
Like I said in the comment on my post. Turns out I'm an idiot. When displaying the preview, I used this.person.personData.imagePreview . When a user fetches a project from the DB, I just did this.person.personData = response.data. That works fine, apart from the fact that I had a different name for imagePreview on my backend. So I manually set it on the same load method when fetching from the DB like: this.person.personData.imagePreview = this.loadedPersonData.file. For some reason, that screwed with the reactivity of Vue.

Element is undefined because it is not rendered yet. How to wait for it?

In my Vue app I have an image element with a bound src. this code is in a stepper. In one step the user selects a picture to upload an in the next step the image gets shown (which works as intended). However I am trying to initiate a library on the element in the next step (the Taggd library) but the element seems to be undefined.
I tried the nextTick() to wait for the image to load but without luck.
the image element:
<div class="orientation-landscape">
<div class="justify-center q-px-lg">
<img v-if="photo.url" :src="photo.url" id="workingPhoto"
style="width: 80vw;" ref="workingPhoto"/>
</div>
</div>
The functions. I first use uploadFile to set the url of the image element and go to the next step where the image will be loaded. then I call initTaggd() on the nextTick however that fails because the element is undefined.
uploadFile(file) {
const self = this;
self.photo.file = file;
self.setPhotoUrl(file);
self.$refs.stepper2.next();
console.log('We should be at next step now. doing the init');
self.nextTick(self.initTaggd());
},
setPhotoUrl(file) {
const self = this;
self.photo.url = URL.createObjectURL(file);
console.log('ping1');
},
initTaggd() {
const self = this;
const image = document.getElementById('workingPhoto');
console.log('image:', image); //THIS RETURNS UNDEFINED
console.log('Trying ANOTHER element by refs:', self.$refs.stepper2); // This returns the element
console.log('trying the real element by reference', self.$refs.workingPhoto); // Returns undefined again
const taggd = new Taggd(image); //All this here fails because image is undefined.
console.log('ping2.5');
taggd.setTags([
self.createTag(),
self.createTag(),
self.createTag(),
]);
console.log('ping3');
},
I think I am looking for a way to wait for the image to fully load before calling initTaggd() but I am lost on how to achieve this.
You could listen for the load event:
<img
v-if="photo.url"
id="workingPhoto"
ref="workingPhoto"
:src="photo.url"
style="width: 80vw;"
#load="initTaggd"
/>