Unhandled Rejection outside Promise? - javascript

So basically I am running some code that queries a graphql api, and checks whether the data field inside is null (meaning there are no hits for the query), like so:
// check if the items have available data.
// if not, throw an error message saying which ones did not have data.
const testIfDataInDB = await Promise.all(objIDs.map(objID => {
return fetch("/api/graphql", {
method: "POST",
headers: headers,
body: JSON.stringify({
query: "query get_object_with_obj_number($objectNumber: String!) { constructionDetail(objectNumber: $objectNumber) { objectNumber } }",
variables: {
objectNumber: objID
}
}
)
}).then(async (res) => {
return {
responseData: await res.json(),
objID: objID
}
}
)
}));
const itemsDataNotFound = testIfDataInDB.filter(o =>
o.responseData?.data?.constructionDetail === null);
let errString = "";
if (itemsDataNotFound.length > 0) {
itemsDataNotFound.forEach(obj => {
errString = errString + `${obj.objID}, `;
});
errString = errString.slice(0, errString.length - 2);
console.log(errString);
throw new Error(errString);
}
// ... do some object transformations ...
// proceed to post some items into another db using fetch.
const response = await Promise.all(objectsArr.map((obj, index) => {
const body = JSON.stringify(obj);
if (update && index === 0) {
const fetchUrl = `${baseFetchUrl}/${parentItemMetadata._id}`
return fetch(
fetchUrl, {
method: "PUT",
headers: headers,
body: body
}
).then(res => res.json())
}
return fetch(
baseFetchUrl, {
method: "POST",
headers: headers,
body: body
}
).then(res => res.json())
}))
console.log(response);
return response;
}
full code for this part
and the way im calling this code inside my react component:
//defined in parent
const saveMultipleItems = async (
objIDs: string[],
update: boolean
) => {
const parentItemMetaData: TypeLabelItemMetaData = {
createdBy: currentItem?.createdBy || "",
createdAt: currentItem?.createdAt || "",
updatedBy: currentItem?.updatedBy || "",
updatedAt: currentItem?.updatedAt || "",
_id: currentItem?._id || "",
collection: currentItem?.collection || ""
}
try {
saveMultiple(
objIDs,
labelType,
values as TypeLabelState,
parentItemMetaData,
user,
update
)
} catch (e) {
console.warn(e.message);
} finally {
fetchItems();
}
// called in child component
onSubmit={(e) => {
e.preventDefault();
console.log("submitting a series")
try {
const pNumbersArray = generateArray(fromObjNumber, toObjNumber);
saveSeriesFn(pNumbersArray, editMode);
} catch (e) {
console.log("catched error")
alert("Saving series failed with message " + e.message);
}
}
}
My plan was to throw an error, and react to this error somewhere where I can show an alert saying that some items are not available to be saved, and abort the saving operation. I kn
I know this may not be the cleanest way to do this (I am also very grateful for sugestions). The problem I am having right now, is that the app crashes with the following:
Unhandled Rejection (Error): P18100405117, P18100405118, P18100405119
saveMultiple
src/app/src/api/savemultiple.ts:70
67 | });
68 | errString = errString.slice(0, errString.length - 2);
69 | console.log(errString);
70 | throw new Error(errString);
| ^ 71 | }
72 |
73 | const objectsArr: SaveTemplateObjType[] = objIDs.map((objID, index) => {
I thought I was not inside a Promise at the moment I threw this Error?

Async/Await is a synthetic sugar for Promises
Your code states: const saveMultiple = async(...
An Async function will always return a Promise. (see refs below)
Your try/catch doesnt take affect in:
try {
saveMultiple(
objIDs,
labelType,
values as TypeLabelState,
parentItemMetaData,
user,
update
)
} catch (e) {
console.warn(e.message);
} finally {
fetchItems();
}
because saveMultiple is async. you need to use:
saveMultiple(
objIDs,
labelType,
values as TypeLabelState,
parentItemMetaData,
user,
update
).catch((e) => {
console.warn(e.message);
}).finally(() => {
fetchItems();
})
From MDN:

Related

How to use discriminated union properly for function return

I'm new to using typescript. I was wondering how to utilize discriminated union for function return. I have an async function that calls 2 endpoints, and I want to correctly type the return value based on each api call results.
So far I managed to created these types:
interface GetDetailSuccess {
status: "success";
data: MovieDetailResult;
}
interface GetDetailFail {
status: "failed";
error: any;
}
interface GetCastSuccess {
status: "success";
data: MovieCastResult
}
interface GetCastFail {
status: "failed";
error: any;
}
type MovieDetail = GetDetailSuccess | GetDetailFail;
type MovieCast = GetCastSuccess | GetCastFail;
type ReturnValue = {
movieDetail: MovieDetail;
movieCast: MovieCast;
};
Here is the simplified version of the function that I managed to create so far:
export const getMovieDetailAndCast = async ():Promise<ReturnValue> => {
const movDet = {} as MovieDetail;
const movCas = {} as MovieCast;
await Promise.allSettled([
api.getMovieDetail(),
api.getMovieCast(),
])
.then((responses) => {
responses.forEach((res, index) => {
if (index === 0) {
if (res.status === "fulfilled") {
movDet.status = "success";
if (movDet.status === "success") {
movDet.data = res.value.data;
}
}
if (res.status === "rejected") {
movDet.status = "failed";
if (movDet.status === "failed") {
movDet.error = res.reason.response.data.status_message;
}
}
}
if (index === 1) {
if (res.status === "fulfilled") {
movCas.status = "success";
if (movCas.status === "success") {
movCas.data = res.value.data;
}
}
if (res.status === "rejected") {
movCas.status = "failed";
if (movCas.status === "failed") {
movCas.error = res.reason.response.data.status_message;
}
}
}
});
})
.catch((err) => {
console.error(err);
});
return {
movieDetail: movDet,
movieCast: movCas,
};
}
So far the IDE doesn't yell at me for any error, but I do wonder if what I am doing is correct. Especially the part on how to narrowing the type and the part where I assigned an empty objects using as. Is there anything that I could to improve the coding above? Any feedback would be appreciated
It's not clear what you want to achieve using different types for success and failure. Usually, the easiest way to get if it is a success or failure is checking if the error property is defined or if the status property is "success".
I think you should narrow your types like so to reduce complexity:
export const enum GetStatus {
PENDING = "pending",
SUCCESS = "success",
FAILED = "failed"
}
export interface GetDetail {
status: GetStatus;
data: MovieDetailResult | undefined;
error: any;
}
export interface GetCast {
status: GetStatus;
data: MovieCastResult | undefined;
error: any;
}
export interface DetailAndCast {
movieDetail: GetDetail;
movieCast: GetCast;
};
Then, if you follow this suggestion you might want to keep track of your call with a "pending" status.
export const getMovieDetailAndCast: () => Promise<DetailAndCast> = async () => {
const movieDetail: GetDetail = {status: GetStatus.PENDING, data: undefined, error: undefined};
const movieCast: GetCast = {status: GetStatus.PENDING, data: undefined, error: undefined};
await Promise.all([
api.getMovieDetail(),
api.getMovieCast(),
])
.then(responses => {
responses.foreach((res, index) => {
const returnValue = index === 0 ? movieDetail : movieCast;
if (res.status === "fulfilled") {
returnValue.status = GetStatus.SUCCESS;
returnValue.data = res.value.data;
} else if (res.status === "rejected") {
returnValue.status = GetStatus.FAILED;
returnValue.error = res.reason.response.data.status_message;
}
});
})
.catch(err => console.error(err));
return {movieDetail, movieCast};
}

Broadcasting to all clients with Deno websocket

I want to add notifications to an application I've developed.
Unfortunately, Deno has removed the ws package.(https://deno.land/std#0.110.0/ws/mod.ts)
That's why I'm using the websocket inside the denon itself. Since it doesn't have many functions, I have to add some things myself.
For example, sending all messages to open clients.
What I want to do is when the pdf is created, a (data, message) comes from the socket and update the notifications on the page according to the incoming data.
I keep all open clients in a Map. and when the pdf is created, I return this Map and send it to all sockets (data, message).
However, this works for one time.
server conf...
import {
path,
paths,
ctid,
} from "../deps.ts";
const users = new Map();
const sockets = new Map()
const userArr = [];
export const startNotif = (socket,req) => {
const claims = req.get("claims");
const org = req.get("org");
claims.org = org;
console.log("connected")
users.set(claims.sub, {"username":claims.sub,"socket":socket})
users.forEach((user)=>{
if(userArr.length === 0){
userArr.push(user)
}
else if(userArr.every((w)=> w.username !== user.username) )
userArr.push(user)
})
sockets.set(org, userArr)
function broadcastMessage(message) {
sockets.get(org).map((u)=>{
console.log(u.socket.readyState)
u.socket.send(message)
})
}
if (socket.readyState === 3) {
sockets.delete(uid)
return
}
const init = (msg) => {
socket.send(
JSON.stringify({
status: "creating",
})
);
};
const ondata = async (msg) => {
const upfilepath = path.join(paths.work, `CT_${msg.sid}_report.pdf`);
try {
const s=await Deno.readTextFile(upfilepath);
if(s){
socket.send(
JSON.stringify({
status: "end",
})
);
} else {
socket.send(
JSON.stringify({
status: "creating",
})
);
}
} catch(e) {
if(e instanceof Deno.errors.NotFound)
console.error('file does not exists');
}
};
const end = () => {
try {
const endTime = Date.now()
const msg = "Your PDF has been created"
const id = ctid(12) // random id create
broadcastMessage(
JSON.stringify({
id: id,
date: endTime,
status: "done",
message: msg,
read: 'negative',
action: 'pdf'
})
);
} catch (e) {
console.log(400, "Cannot send.", e);
}
}
socket.onmessage = async (e) => {
const cmd = JSON.parse(e.data);
if(cmd.bid === 'start'){
await init(cmd)
}
if(!cmd.bid && cmd.sid){
await ondata(cmd)
}
if(cmd.bid === 'end'){
await end();
}
}
socket.onerror = (e) => {
console.log(e);
};
}
client conf...
export const webSocketHandler = (request) =>
new Promise((res, rej) => {
let url;
if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
url = `http://localhost:8080/api/notifications/ws`.replace('http', 'ws');
} else {
url = `${window.location.origin}/api/notifications/ws`.replace('http', 'ws');
}
const token = JSON.parse(sessionStorage.getItem('token'));
const orgname = localStorage.getItem('orgname');
const protocol = `${token}_org_${orgname}`;
const socket = new WebSocket(url, protocol);
const response = Object.create({});
socket.onopen = function () {
socket.send(
JSON.stringify({
bid: 'start',
})
);
};
socket.onmessage = function (event) {
response.data = JSON.parse(event.data);
if (response.data.status === 'creating') {
socket.send(
JSON.stringify({
sid: request.sid,
})
);
} else if (response.data.status === 'end') {
socket.send(
JSON.stringify({
bid: 'end',
})
);
} else if (response.data.status === 'done') {
try {
res(response);
} catch (err) {
rej(err);
}
}
};
socket.onclose = function (event) {
response.state = event.returnValue;
};
socket.onerror = function (error) {
rej(error);
};
});
onclick function of button I use in component...
const donwloadReport = async (type) => {
const query = `?sid=${sid}&reportType=${type}`;
const fileName = `CT_${sid}_report.${type}`;
try {
type === 'pdf' && setLoading(true);
const response = await getScanReportAction(query);
const request = {
sid,
};
webSocketHandler(request)
.then((data) => {
console.log(data);
dispatch({
type: 'update',
data: {
id: data.data.id,
date: data.data.date,
message: data.data.message,
action: data.data.action,
read: data.data.read,
},
});
})
.catch((err) => {
console.log(err);
});
if (type === 'html') {
downloadText(response.data, fileName);
} else {
const blobUrl = await readStream(response.data);
setLoading(false);
downloadURL(blobUrl, fileName);
}
} catch (err) {
displayMessage(err.message);
}
};
Everything works perfectly the first time. When I press the download button for the pdf, the socket works, then a data is returned and I update the notification count with the context I applied according to this data.
Later I realized that this works in a single tab. When I open a new client in the side tab, my notification count does not increase. For this, I wanted to keep all sockets in Map and return them all and send a message to each socket separately. But in this case, when I press the download button for the second time, no data comes from the socket.
Actually, I think that I should do the socket initialization process on the client in the context. When you do this, it starts the socket 2 times in a meaningless way.
In summary, consider an application with organizations and users belonging to those organizations. If the clients of A, B, C users belonging to X organization are open at the same time and user A pressed a pdf download button, I want A, B, C users to be notified when the pdf is downloaded.
I would be very grateful if someone could show me a way around this issue.
Have you looked at the BroadcastChannel API? Maybe that could solve your issue. See for example:
Deno specific: https://medium.com/deno-the-complete-reference/broadcast-channel-in-deno-f76a0b8893f5
Web/Browser API: https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API

Mock server error - The script has an unsupported MIME type ('text/html')

When i running my app i get this error :
I'm using msw versin: 0.39.2
My msw file in the public folder :
and this is my msw file :
/* eslint-disable */
/* tslint:disable */
/**
* Mock Service Worker (0.39.2).
* #see https://github.com/mswjs/msw
* - Please do NOT modify this file.
* - Please do NOT serve this file on production.
*/
const INTEGRITY_CHECKSUM = '*****'
const bypassHeaderName = '*****'
const activeClientIds = new Set()
self.addEventListener('install', function () {
return self.skipWaiting()
})
self.addEventListener('activate', async function (event) {
return self.clients.claim()
})
self.addEventListener('message', async function (event) {
const clientId = event.source.id
if (!clientId || !self.clients) {
return
}
const client = await self.clients.get(clientId)
if (!client) {
return
}
const allClients = await self.clients.matchAll()
switch (event.data) {
case 'KEEPALIVE_REQUEST': {
sendToClient(client, {
type: 'KEEPALIVE_RESPONSE',
})
break
}
case 'INTEGRITY_CHECK_REQUEST': {
sendToClient(client, {
type: 'INTEGRITY_CHECK_RESPONSE',
payload: INTEGRITY_CHECKSUM,
})
break
}
case 'MOCK_ACTIVATE': {
activeClientIds.add(clientId)
sendToClient(client, {
type: 'MOCKING_ENABLED',
payload: true,
})
break
}
case 'MOCK_DEACTIVATE': {
activeClientIds.delete(clientId)
break
}
case 'CLIENT_CLOSED': {
activeClientIds.delete(clientId)
const remainingClients = allClients.filter((client) => {
return client.id !== clientId
})
// Unregister itself when there are no more clients
if (remainingClients.length === 0) {
self.registration.unregister()
}
break
}
}
})
// Resolve the "main" client for the given event.
// Client that issues a request doesn't necessarily equal the client
// that registered the worker. It's with the latter the worker should
// communicate with during the response resolving phase.
async function resolveMainClient(event) {
const client = await self.clients.get(event.clientId)
if (client.frameType === 'top-level') {
return client
}
const allClients = await self.clients.matchAll()
return allClients
.filter((client) => {
// Get only those clients that are currently visible.
return client.visibilityState === 'visible'
})
.find((client) => {
// Find the client ID that's recorded in the
// set of clients that have registered the worker.
return activeClientIds.has(client.id)
})
}
async function handleRequest(event, requestId) {
const client = await resolveMainClient(event)
const response = await getResponse(event, client, requestId)
// Send back the response clone for the "response:*" life-cycle events.
// Ensure MSW is active and ready to handle the message, otherwise
// this message will pend indefinitely.
if (client && activeClientIds.has(client.id)) {
;(async function () {
const clonedResponse = response.clone()
sendToClient(client, {
type: 'RESPONSE',
payload: {
requestId,
type: clonedResponse.type,
ok: clonedResponse.ok,
status: clonedResponse.status,
statusText: clonedResponse.statusText,
body:
clonedResponse.body === null ? null : await clonedResponse.text(),
headers: serializeHeaders(clonedResponse.headers),
redirected: clonedResponse.redirected,
},
})
})()
}
return response
}
async function getResponse(event, client, requestId) {
const { request } = event
const requestClone = request.clone()
const getOriginalResponse = () => fetch(requestClone)
// Bypass mocking when the request client is not active.
if (!client) {
return getOriginalResponse()
}
// Bypass initial page load requests (i.e. static assets).
// The absence of the immediate/parent client in the map of the active clients
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
// and is not ready to handle requests.
if (!activeClientIds.has(client.id)) {
return await getOriginalResponse()
}
// Bypass requests with the explicit bypass header
if (requestClone.headers.get(bypassHeaderName) === 'true') {
const cleanRequestHeaders = serializeHeaders(requestClone.headers)
// Remove the bypass header to comply with the CORS preflight check.
delete cleanRequestHeaders[bypassHeaderName]
const originalRequest = new Request(requestClone, {
headers: new Headers(cleanRequestHeaders),
})
return fetch(originalRequest)
}
// Send the request to the client-side MSW.
const reqHeaders = serializeHeaders(request.headers)
const body = await request.text()
const clientMessage = await sendToClient(client, {
type: 'REQUEST',
payload: {
id: requestId,
url: request.url,
method: request.method,
headers: reqHeaders,
cache: request.cache,
mode: request.mode,
credentials: request.credentials,
destination: request.destination,
integrity: request.integrity,
redirect: request.redirect,
referrer: request.referrer,
referrerPolicy: request.referrerPolicy,
body,
bodyUsed: request.bodyUsed,
keepalive: request.keepalive,
},
})
switch (clientMessage.type) {
case 'MOCK_SUCCESS': {
return delayPromise(
() => respondWithMock(clientMessage),
clientMessage.payload.delay,
)
}
case 'MOCK_NOT_FOUND': {
return getOriginalResponse()
}
case 'NETWORK_ERROR': {
const { name, message } = clientMessage.payload
const networkError = new Error(message)
networkError.name = name
// Rejecting a request Promise emulates a network error.
throw networkError
}
case 'INTERNAL_ERROR': {
const parsedBody = JSON.parse(clientMessage.payload.body)
console.error(
`\
[MSW] Uncaught exception in the request handler for "%s %s":
${parsedBody.location}
This exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error, as it indicates a mistake in your code. If you wish to mock an error response, please see this guide: https://mswjs.io/docs/recipes/mocking-error-responses\
`,
request.method,
request.url,
)
return respondWithMock(clientMessage)
}
}
return getOriginalResponse()
}
self.addEventListener('fetch', function (event) {
const { request } = event
const accept = request.headers.get('accept') || ''
// Bypass server-sent events.
if (accept.includes('text/event-stream')) {
return
}
// Bypass navigation requests.
if (request.mode === 'navigate') {
return
}
// Opening the DevTools triggers the "only-if-cached" request
// that cannot be handled by the worker. Bypass such requests.
if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
return
}
// Bypass all requests when there are no active clients.
// Prevents the self-unregistered worked from handling requests
// after it's been deleted (still remains active until the next reload).
if (activeClientIds.size === 0) {
return
}
const requestId = uuidv4()
return event.respondWith(
handleRequest(event, requestId).catch((error) => {
if (error.name === 'NetworkError') {
console.warn(
'[MSW] Successfully emulated a network error for the "%s %s" request.',
request.method,
request.url,
)
return
}
// At this point, any exception indicates an issue with the original request/response.
console.error(
`\
[MSW] Caught an exception from the "%s %s" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,
request.method,
request.url,
`${error.name}: ${error.message}`,
)
}),
)
})
function serializeHeaders(headers) {
const reqHeaders = {}
headers.forEach((value, name) => {
reqHeaders[name] = reqHeaders[name]
? [].concat(reqHeaders[name]).concat(value)
: value
})
return reqHeaders
}
function sendToClient(client, message) {
return new Promise((resolve, reject) => {
const channel = new MessageChannel()
channel.port1.onmessage = (event) => {
if (event.data && event.data.error) {
return reject(event.data.error)
}
resolve(event.data)
}
client.postMessage(JSON.stringify(message), [channel.port2])
})
}
function delayPromise(cb, duration) {
return new Promise((resolve) => {
setTimeout(() => resolve(cb()), duration)
})
}
function respondWithMock(clientMessage) {
return new Response(clientMessage.payload.body, {
...clientMessage.payload,
headers: clientMessage.payload.headers,
})
}
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = (Math.random() * 16) | 0
const v = c == 'x' ? r : (r & 0x3) | 0x8
return v.toString(16)
})
}
Any help?
The problem was in my package.json
When you add homepage to the package.json, the msw don't know the url.
I removed the homepage and restart my app.
The issue is your web-server: it’s returning a Content-type of 'text-html'. I bet you have misspelled the name of the script and it’s sending an HTML 404 page.

JavaScript PromiseAll allSettled does not catch the rejected

I have a sns lambda function that returns void (https://docs.aws.amazon.com/lambda/latest/dg/with-sns.html). This event orderId and one message'status: success' are what I'm publishing. I check if the 'orderId' exists in my data database in the sns subscription lambda event. If it already exists, update the database; if it doesn't, console error it.
I created an integration test in which I transmit a random 'uuid' that isn't a valid 'orderId,' but it appears that my promise doesn't capture the'rejected'. It should show in console error failed to find order... I'm not sure where I'm going wrong. Also My promise syntax looks complicated, is there any neat way, I can do it. Thank you in advance 🙏🏽
This is sns event, which listen the publishing
interface PromiseFulfilledResult<T> {
status: "fulfilled" | "rejected";
value: T;
}
const parseOrdersFromSns = (event: SNSEvent) => {
try {
return event.Records.flatMap((r) => JSON.parse(r.Sns.Message))
} catch (error) {
console.error('New order from SNS failed at parsing orders', { event }, error)
return []
}
}
export const handlerFn = async (event: SNSEvent): Promise<void> => {
const orders = parseOrdersFromSns(event)
if (orders.length === 0) return
const existingOrdersPromiseResult = await Promise.allSettled(
orders.map(
async (o) => await findOrderStateNode(tagOrderStateId(o.orderId))
)
); // This returns of data if the order exsiit other it will return undefined
const existingOrders = existingOrdersPromiseResult // should returns arrays of data
.filter(({ status }) => status === "fulfilled")
.map(
(o) =>
(
o as PromiseFulfilledResult<
TaggedDatabaseDocument<
OrderStateNode,
TaggedOrderStateId,
TaggedOrderStateId
>
>
).value
);
const failedOrders = existingOrdersPromiseResult.filter( // should stop the opeartion if the data is exsit
({ status }) => status === "rejected"
);
failedOrders.forEach((failure) => {
console.error("failed to find order", { failure });
});
const updateOrder = await Promise.all(
existingOrders.map((o) => {
const existingOrderId = o?.pk as TaggedOrderStateId;
console.log({ existingOrderId }); // Return Undefined
})
);
return updateOrder;
};
this is my test suite
describe('Creating and updating order', () => {
integrationTest(
'Creating and updating the order',
async (correlationId: string) => {
CorrelationIds.set('x-correlation-id', correlationId)
const createdOrder = await createNewOrder(correlationId) // This create random order
if (!createdOrder.id) {
fail('order id is not defined')
}
const order = await getOrder(createdOrder.id)
// Add new order to table
await initializeOrderState([order])
const exisitingOrder = await findOrderStateNode(tagOrderStateId(order.id))
if (!exisitingOrder) fail(`Could not existing order with this orderId: ${order.id}`)
const event = {
Records: [
{
Sns: {
Message: JSON.stringify([
{
orderId: uuid(), // random order it
roundName,
startTime,
},
{
orderId: order.id,
roundName,
startTime,
},
{
orderId: uuid(),
roundName,
startTime,
},
]),
},
},
],
} as SNSEvent
await SnsLambda(event)
const updateOrderState = await findOrderStateNode(tagOrderStateId(order.id))
expect(updateOrderState?.status).toEqual('success')
},
)
})

Called two functions on route watch change in vuejs

As I am new in Vuejs, It will be very easy for others, but for me I cannot get it right, I search a lot but cannot get the expected answer
Below is my code
watch: {
$route () {
this.newsData = []
this.loadNewsByCategory()
this.category = {}
this.getCategoryData()
}
},
created () {
this.getCategoryData()
this.loadNewsByCategory()
},
methods () {
async getCategoryData() {
// console.log('called category data')
try {
await firebase.firestore().collection('categories').doc(this.$route.params.id).get().then((doc) => {
if (doc.exists) {
this.category = doc.data()
}
})
} catch (error) {
console.log(error) // this line show the error I've post below
this.$q.notify({ type: 'negative', message: error.toString() })
}
},
async loadNewsByCategory() {
// console.log('load news')
try {
var db = firebase.firestore()
var first = db.collection('posts')
.where('publishedAt', '<=', new Date())
.where('categories', 'array-contains', this.$route.params.id)
.orderBy('publishedAt', 'desc')
.limit(12)
return await first.get().then((documentSnapshots) => {
documentSnapshots.forEach((doc) => {
const news = {
id: doc.id,
slug: doc.data().slug,
title: doc.data().title,
image: doc.data().image.originalUrl,
publishedAt: dateFormat(doc.data().publishedAt.toDate(), 'dS mmm, yyyy')
}
this.newsData.push(news)
})
this.lastVisible = documentSnapshots.docs[documentSnapshots.docs.length - 1]
})
} catch (error) {
this.$q.notify({ type: 'negative', message: error.toString() })
}
}
}
In my code, when initialize I call two functions to query data from firebase and it's working as expected. but when the route change for example: from getdata/1 to getdata/2 one function i.e., loadNewsByCategory() is working but others throw error like below
TypeError: u.indexOf is not a function
at VueComponent.getCategoryData (getdata.vue?3b03:102)
at VueComponent.created (getdata.vue?3b03:92)
Thank you in advance

Categories

Resources