Meteor Tutorial - Tracker is not defined - javascript

I'm doing the Meteor + Ionic tutorial and, after having corrected several errors, I'm completely stuck with one.
Changing my main.ts code with this one
import 'meteor-client';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { MeteorObservable } from 'meteor-rxjs';
import { Meteor } from 'meteor/meteor';
import { AppModule } from './app.module';
Meteor.startup(() => {
const subscription = MeteorObservable.autorun().subscribe(() => {
if (Meteor.loggingIn()) {
return;
}
setTimeout(() => subscription.unsubscribe());
platformBrowserDynamic().bootstrapModule(AppModule);
});
});
Throws the next error
ReferenceError: Tracker is not defined at autorun
(http://localhost:8100/build/vendor.js:178469:13) at
Observable._subscribe
(http://localhost:8100/build/vendor.js:178480:27) at
Observable._trySubscribe
(http://localhost:8100/build/vendor.js:23023:25) at
Observable.subscribe (http://localhost:8100/build/vendor.js:23011:93)
at http://localhost:8100/build/main.js:57:65 at maybeReady
(http://localhost:8100/build/vendor.js:123856:57) at
HTMLDocument.loadingCompleted
(http://localhost:8100/build/vendor.js:123868:9) at t.invokeTask
(http://localhost:8100/build/polyfills.js:3:15660) at r.runTask
(http://localhost:8100/build/polyfills.js:3:10834) at e.invokeTask [as
invoke] (http://localhost:8100/build/polyfills.js:3:16794)
I've checked all the dependencies and everything is ok

My guess is that subscribe isn't directly connected to autorun. Try splitting the two up with this:
const sub = MeteorObservable.subscribe('mySubscriptionForSomeData');
const autorun = MeteorObservable.autorun();
Observable.merge(sub, autorun).subscribe(() => {
this.jobs = SomeCollection.find().zone(); // Data is ready here
}, (err) => {
console.log(err); // error fetching data
}, () => {
console.log('This will print always, whether data is fetched or err happened');
});
Source: https://github.com/Urigo/meteor-rxjs/issues/98

A fresh node install solved the problem

Related

How to use Peer.js in Next.js with TypeScript?

Next.js runs on server side also, so Peer.js raise error when using Next.js. Here one says: https://stackoverflow.com/a/66292100/239219
this is probably because peer js is performing some side effect during import.
He propose this:
useEffect(() => {
import('peerjs').then(({ default: Peer }) => {
// Do your stuff here
});
}, [])
But I need DataConnection as using Typescript, and also asign it to a useState. would you show an example how?
This is what I put togeter, but TypesScript raise errors:
useEffect(() => {
import('peerjs').then(({ default: Peer, DataConnection }) => {
const peer = new Peer(localStorage.token)
peer.on('connection', (conn: DataConnection) => {
console.log('Connected to peer:', conn)
conn.on('data', (data) => {
console.log('Received data:', data)
})
})
return () => {
peer.destroy()
}
})
}, [])
like: 'DataConnection' refers to a value, but is being used as a type here. Did you mean 'typeof DataConnection'?
You can use a type-only import (introduced in version 3.8) at the top of the file:
import type { DataConnection } from "peerjs";
This import will be erased in the output, so rest assured that this will not import it "early".
Or if that doesn't fancy you, you can also "inline" the import:
peer.on('connection', (conn: import("peerjs").DataConnection) => {
Looks weird, but when import(...) is used as a type, it resolves to the namespace that importing the module would give you.

Error trying to login on Azure: BrowserAuthError

I'm getting an error trying to login with Azure + TypeScript/JavaScript. The problem is when the user logs in and needs to get redirected to another page. When the response from login is OK, the page remains blank and I need to refresh manually.
This is my config file:
import { Configuration, LogLevel } from "#azure/msal-browser"
export const msalConfig:Configuration = {
auth: {
clientId: process.env.AZURE_CLIENT_LOGIN || "",
authority: "https://login.microsoftonline.com/" + process.env.AZURE_AUTH_LOGIN,
redirectUri: "/admin/dashboard"
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
},
system: {
loggerOptions: {
loggerCallback: (level: any, message: any, containsPii: any) => {
if (containsPii) {
return;
}
switch (level) {
case LogLevel.Error:
console.error(message);
return;
case LogLevel.Info:
console.info(message);
return;
case LogLevel.Verbose:
console.debug(message);
return;
case LogLevel.Warning:
console.warn(message);
return;
}
}
}
}
}
export const loginRequest = {
scopes: ["User.Read"]
};
export const graphConfig = {
graphMeEndpoint: "Enter_the_Graph_Endpoint_Herev1.0/me"
};
And this is my index page:
import React, { useEffect } from 'react';
import type { NextPage } from "next";
import { useRouter } from 'next/router';
import { useMsal } from '#azure/msal-react';
import { useIsAuthenticated } from '#azure/msal-react';
import { loginRequest } from '../services/azureLoginApi';
const Home: NextPage = () => {
const router = useRouter()
const { instance } = useMsal()
const isAuthenticated = useIsAuthenticated()
const redirectToAzureLogin = () => {
instance.loginRedirect(loginRequest).catch((e:any) => {
console.log(e);
});
}
const redirectToDashboard = () => {
router.push('/admin/dashboard')
}
useEffect(()=>{
if(isAuthenticated)
redirectToDashboard()
else
redirectToAzureLogin()
},[])
return (
<div className="index">
</div>
);
};
export default Home;
On console, I get this message:
BrowserAuthError: interaction_in_progress: Interaction is currently in progress. Please ensure that this interaction has been completed before calling an interactive API. For more visit: aka.ms/msaljs/browser-errors.
at BrowserAuthError.AuthError [as constructor] (AuthError.js?d98c:27:1)
at new BrowserAuthError (BrowserAuthError.js?be02:197:1)
at Function.BrowserAuthError.createInteractionInProgressError (BrowserAuthError.js?be02:264:1)
at BrowserCacheManager.setInteractionInProgress (BrowserCacheManager.js?6011:886:23)
at PublicClientApplication.ClientApplication.preflightInteractiveRequest (ClientApplication.js?9c57:777:1)
at PublicClientApplication.ClientApplication.preflightBrowserEnvironmentCheck (ClientApplication.js?9c57:762:1)
at PublicClientApplication.eval (ClientApplication.js?9c57:220:1)
at step (_tslib.js?89f4:75:1)
at Object.eval [as next] (_tslib.js?89f4:56:46)
at eval (_tslib.js?89f4:49:1)
at new Promise (<anonymous>)
at __awaiter (_tslib.js?89f4:45:1)
at PublicClientApplication.ClientApplication.acquireTokenRedirect (ClientApplication.js?9c57:214:25)
at PublicClientApplication.eval (PublicClientApplication.js?1b7b:63:1)
at step (_tslib.js?89f4:75:1)
at Object.eval [as next] (_tslib.js?89f4:56:46)
at eval (_tslib.js?89f4:49:1)
at new Promise (<anonymous>)
at __awaiter (_tslib.js?89f4:45:1)
at PublicClientApplication.loginRedirect (PublicClientApplication.js?1b7b:58:25)
at redirectToAzureLogin (index.tsx?db76:18:14)
at eval (index.tsx?db76:31:7)
at invokePassiveEffectCreate (react-dom.development.js?61bb:23487:1)
at HTMLUnknownElement.callCallback (react-dom.development.js?61bb:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js?61bb:3994:1)
at invokeGuardedCallback (react-dom.development.js?61bb:4056:1)
at flushPassiveEffectsImpl (react-dom.development.js?61bb:23574:1)
at unstable_runWithPriority (scheduler.development.js?3069:468:1)
at runWithPriority$1 (react-dom.development.js?61bb:11276:1)
at flushPassiveEffects (react-dom.development.js?61bb:23447:1)
at eval (react-dom.development.js?61bb:23324:1)
at workLoop (scheduler.development.js?3069:417:1)
at flushWork (scheduler.development.js?3069:390:1)
at MessagePort.performWorkUntilDeadline (scheduler.development.js?3069:157:1)
The page remains blank until I give a manual refresh on it. With the manual refresh, the redirect works, but without it the page remains freezed.
I've tried some solutions on StackOverflow and other blogs but didn't work out.
Thank you all for any help you may give!
change instance.loginRirect to instance.loignPopup, that would solve that
Problem solved: the point was the useEffect without dependencies. Adding it solved the problem, now the redirect works without needing to manually update the page.

Mock Service Worker / Node isn't working and I can't see why

If anyone can spot whatever's wrong with this code, I'd really appreciate. Not seeing an issue myself, but it's failing.
import React from "react"
import {setupServer} from "msw/node"
import {rest} from "msw"
describe("mocking apis", () => {
const testCall = jest.fn()
const server = setupServer(
...[
rest.get("/test", (req, res, ctx) => {
console.log('This line is never run')
testCall()
return res(ctx.json({message: "success"}))
}),
]
)
test("test", async () => {
server.listen()
fetch("/test", {method: "GET"})
expect(testCall).toHaveBeenCalled()
server.close();
})
})
I also had this problem. After a while I realized the cause. In my src/setupTests.js file I had:
import { enableFetchMocks } from 'jest-fetch-mock';
...
enableFetchMocks();
So, fetch() was not being called at all.
I made 3 changes to the posted code to get it to work:
Import and call disableFetchMocks().
Add await before fetch(....
Change the URL to http://localhost/test, to address a test error that said I needed to use an absolute URL.
Here is the working code (cleaned up to AirB&B style by PyCharm):
import { setupServer } from 'msw/node';
import { rest } from 'msw';
import { disableFetchMocks } from 'jest-fetch-mock';
describe('mocking apis', () => {
const testCall = jest.fn();
const server = setupServer(
...[
rest.get('http://localhost/test', (req, res, ctx) => {
console.log('This line is run');
testCall();
return res(ctx.json({ message: 'success' }));
}),
],
);
test('test', async () => {
disableFetchMocks();
server.listen();
await fetch('http://localhost/test', { method: 'GET' });
expect(testCall).toHaveBeenCalled();
server.close();
});
});
When you run your tests these run in a node environment, in this fetch function does not exist (it means: global.fetch) for that reason you need to make a polyfill.
I recommend installing the npm package 'whatwg-fetch'
npm install whatwg-fetch
and use it like this:
import 'whatwg-fetch';
This video could help

Node JS : Route.get() requires a callback function but got a [object Undefined] While using ES6 Modules

Route File
scoreboardroute.js
import { scoreRouteController } from '../controllers/scoreboardcontroller';
const SCOREROUTE = app => {
app.route('/getAllScores').get(scoreRouteController.getAllScores);
};
export { SCOREROUTE };
Controller File
scoreboardcontroller.js
import { scoreBoardModel } from '../model/scoreboardmodel';
class scoreRouteController {
getAllScores = (req, res) => {
scoreBoardModel.getAllScoresList((err, response) => {
if (err) {
res.send(err);
}
res.send(response);
});
};
}
export { scoreRouteController };
Model File:
scoreboardmodel.js
import { db } from './db';
class scoreBoardModel {
getAllScoresList = callback => {
db.query('Select * from users', (err,response) => {
callback(err, response);
});
}
};
export { scoreBoardModel };
I was trying to use ES6 features like class and arrow functions inside my application. While I'm trying to execute this code it hit the following error. I don't know what went wrong. And I'm really new for node JS server.
So, Can anyone please help me to get rid of this error.
Error:
node_modules/express/lib/router/route.js:202
throw new Error(msg);
^
Error: Route.get() requires a callback function but got a [object Undefined]
at Route.(anonymous function) [as get] (/node_modules/express/lib/router/route.js:202:15)
at SCOREROUTE (/app/routes/scoreboardroute.js:4:32)
at Object. (/server.js:26:1)
at Module._compile (internal/modules/cjs/loader.js:689:30)
I'm finding the answer.
While importing the class I'm using like Object import. So, changed it like
import scoreRouteController from '../controllers/scoreboardcontroller';
And I'm not going to use so many instances for my application. So, I assign static keyword for my every function inside my class.
static getAllScores = (req, res) => {.....
While exporting I was not exporting an Obj. I changed into default class export.
export default scoreRouteController;
And finally, it works.

InvalidStateError while accessing WebSocket

I've configured a simple Vue project using the vue-cli tool:
vue init webpack my-project
Now I want to send some information through a web socket before the page gets rendered. Since I don't want to tie this logic to the Vue component, I have a different js file (named ws.js and based in this):
import Vue from 'vue'
const websocket = new WebSocket('ws://localhost:1234')
const emitter = new Vue({
name: 'emitter',
methods: {
send (message) {
websocket.send(JSON.stringify(message))
}
}
})
export default emitter
When the page loads, I use the emitter object to send some info:
<template>
<div class="hello">
TEST
</div>
</template>
<script>
import emitter from '../ws/ws'
export default {
name: 'HelloWorld',
beforeMount () {
emitter.send('Hello')
}
}
</script>
And I get this error in Firefox console:
[Vue warn]: Error in beforeMount hook: "InvalidStateError: An attempt
was made to use an object that is not, or is no longer, usable"
found in
---> at src/components/HelloWorld.vue
at src/App.vue
What am I doing wrong? Should I attach to a different event listener rather than beforeMount()? If I comment out the WebSocket related lines, the error disappears:
import Vue from 'vue'
// const websocket = new WebSocket('ws://localhost:1234')
const emitter = new Vue({
name: 'emitter',
methods: {
send (message) {
// websocket.send(message)
}
}
})
export default emitter
I need to write for the socket before it's in ready state before sending any message, so based in this answer I have changed ws.js to this:
import Vue from 'vue'
const websocket = new WebSocket('ws://localhost:1234')
// Make the function wait until the connection is made...
function waitForSocketConnection (socket, callback) {
setTimeout(
function () {
if (socket.readyState === 1) {
console.log('Connection is made')
if (callback != null) {
callback()
}
} else {
console.log('wait for connection...')
waitForSocketConnection(socket, callback)
}
}, 5) // wait 5 milisecond for the connection...
}
function sendWaiting (msg) {
waitForSocketConnection(websocket, () => {
console.log('Sending ' + msg)
websocket.send(msg)
console.log('Sent ' + msg)
})
}
const emitter = new Vue({
name: 'emitter',
methods: {
send (message) {
sendWaiting(message)
}
}
})
export default emitter
Now, before sending any message the application checks if the WebSocket is ready and sends it, otherwise it rechecks each 5 milliseconds until it is.

Categories

Resources