Shared Native instance of worker and main thread - nativescript

I want to make a progressbar file download. Calculation of an already loaded file needs to be done in a separate thread. That's just not clear how to pass a variable manager
main.js
import * as MyWorker from 'nativescript-worker-loader!~/utils/DownloadManagerProgress.js';
const { DOWNLOAD_SERVICE } = android.content.Context;
const manager = app.android.context.getSystemService(DOWNLOAD_SERVICE);
const worker = new MyWorker();
worker.postMessage({ manager });
worker.onmessage = function (event) {
console.log(event);
};
worker.onerror = function (err) {
console.log(`An unhandled error occurred in worker: ${err.filename}, line:
${err.lineno} :`);
console.log(err.message);
};
DownloadManagerProgress.js
import 'globals';
global.onmessage = (msg) => {
const { manager } = msg.data;
const query = new android.app.DownloadManager.Query();
const cursor = manager.query(query);
};
Error:
'Uncaught TypeError: Cannot read property \'query\' of undefined'
If I create an object in the worker, an error also appears
DownloadManagerProgress.js
import 'globals';
import * as app from 'application';
global.onmessage = (msg) => {
const { DOWNLOAD_SERVICE } = android.content.Context;
const manager = app.android.context.getSystemService(DOWNLOAD_SERVICE);
const query = new android.app.DownloadManager.Query();
const cursor = manager.query(query);
};
error:
Uncaught TypeError: Cannot read property \'getSystemService\' of undefined'
Сould help me. Thanks.

Related

Type Error Cannot read properties of undefined (reading 'Web3Provider') at fetchingData

It must show console log Big Number instead its showing error.
expected output
error occured
I am new to blockchain. I have connected the private key of hardhat with wallet but its showing Type Error. The expected output and the output which Ive got has attached along with this.
import React, { useState, useEffect } from "react";
import { ethers, BigNumber } from "ethers";
import Web3Modal from "web3modal";
//INTERNAL IMPORT
import {
checkIfWalletConnected,
connectWallet,
connectingWithBooToken,
connectingWithLIfeToken,
connectingWithSingleSwapToken,
connectingWithIWTHToken,
connectingWithDAIToken,
} from "../Utils/appFeatures";
import { IWETHABI } from "./constants";
// import ERC20 from "./ERC20.json";
export const SwapTokenContext = React.createContext();
export const SwapTokenContextProvider = ({ children }) => {
const swap = "Welcome to swap my token";
//USESTATE
const [account, setAccount] = useState("");
const [ether, setEther] = useState("");
const [networkConnect, setNetworkConnect] = useState("");
const [weth9, setWeth9] = useState("");
const [dai, setDai] = useState("");
const [tokenData, setTokenData] = useState([]);
const addToken = [
"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
"0x15Ff10fCc8A1a50bFbE07847A22664801eA79E0f",
"0xAe9Ed85dE2670e3112590a2BB17b7283ddF44d9c",
];
//FETCH DATA
const fetchingData = async () => {
try{
//GET USER ACCOUNT
const userAccount = await checkIfWalletConnected();
setAccount(userAccount);
//CREATE PROVIDER
const web3modal = new Web3Modal();
const connection = await web3modal.connect();
const provider = new ethers.providers.Web3Provider(connection);
//CHECK Balance
const balance = await provider.getBalance(userAccount);
console.log(balance);
}catch(error){
console.log(error);
}
}
useEffect(()=>{
fetchingData();
},[]);
return (
<SwapTokenContext.Provider value={{swap}}>
{children}
</SwapTokenContext.Provider>
);
};
your imports are probably failed try to import like this instead :
const ethers = require("ethers");
const BigNumber = require("ethers");

How to use SSR with Redux in Next.js(Typescript) using next-redux-wrapper? [duplicate]

This question already has an answer here:
next-redux-wrapper TypeError: nextCallback is not a function error in wrapper.getServerSideProps
(1 answer)
Closed 1 year ago.
Using redux with SSR in Next.js(Typescript) using next-redux-wrapper, but getting error on this line
async ({ req, store })
Says, Type 'Promise' provides no match for the signature '(context: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>): Promise<GetServerSidePropsResult<{ [key: string]: any; }>>
Property 'req' does not exist on type 'Store<EmptyObject & { filterReducer: never; }, any> & { dispatch: unknown; }'.
Property 'store' does not exist on type 'Store<EmptyObject & { filterReducer: never; }, any> & { dispatch: unknown; }'
Here is my SSR code:-
export const getServerSideProps: GetServerSideProps = wrapper.getServerSideProps(async ({ req, store }) => {
let { query } = req
let searchCategory = query.category?.toString().toLowerCase().replace(/ /g, "-");
const apolloClient = initializeApollo();
const response = await apolloClient.query({
query: GET_PRODUCT_BY_CATEGORY,
variables: {
numProducts: 10,
category: searchCategory
}
});
await store.dispatch(getProducts(response));
});
You're calling wrapper.getServerSideProps in a wrong way.
Try like the following:
export const getServerSideProps = wrapper.getServerSideProps(
store => async ({req, res, query}) => {
// do your stuff with store and req
}
);
If you're looking for a working demo, you can visit my old answer
This code base could help you. ("next": "10.1.3")
Try using getInitialProps instead of getServerSideProps.
This works in my case. Like code below:
Try
in _app.js
import { wrapper } from '/store';
function MyApp(props) {
const { Component, pageProps } = props;
...
return (
<Component {...pageProps} />
)
}
App.getInitialProps = async props => {
const { Component, ctx } = props;
const pageProps = Component.getInitialProps
? await Component.getInitialProps(ctx)
: {};
//Anything returned here can be accessed by the client
return { pageProps: pageProps, store: ctx.store };
};
export default wrapper.withRedux(App);
store.js file:
const makeStore = props => {
if (!isEmpty(props)) {
return createStore(reducer, bindMiddleware([thunkMiddleware]));
} else {
const { persistStore, persistReducer } = require('redux-persist');
const persistConfig = {
key: 'root',
};
const persistedReducer = persistReducer(persistConfig, reducer); // Create a new reducer with our existing reducer
const store = createStore(
persistedReducer,
bindMiddleware([thunkMiddleware])
); // Creating the store again
store.__persistor = persistStore(store); // This creates a persistor object & push that persisted object to .__persistor, so that we can avail the persistability feature
return store;
}
};
// Export the wrapper & wrap the pages/_app.js with this wrapper only
export const wrapper = createWrapper(makeStore);
in your page:
HomePage.getInitialProps = async ctx => {
const { store, query, res } = ctx;
};

Uncaught ReferenceError: monaco is not defined at new t.MonacoWorkspace

I just build the sample in the example folder (with some modifications to make monaco edit typescript rather json(I'm getting to know how to use monaco api), below in the post) but I got some erros on the console window like below and the autcompleter isn't working, only the syntax highlight.
The error is:
Uncaught ReferenceError: monaco is not defined
at new MonacoWorkspace (main.bundle.js:157068)
at create (main.bundle.js:157028)
at Object.install (main.bundle.js:157034)
at Object../lib/client.js (main.bundle.js:2132)
at __webpack_require__ (main.bundle.js:64)
at Object../lib/main.js (main.bundle.js:2202)
at __webpack_require__ (main.bundle.js:64)
at main.bundle.js:199
at main.bundle.js:202
Uncaught (in promise) Error: Unexpected usage
at EditorSimpleWorker.loadForeignModule (:4200/editor.worker.bundle.js:8995)
at SimpleWorkerServer._handleMessage (:4200/editor.worker.bundle.js:6629)
at Object.handleMessage (:4200/editor.worker.bundle.js:6615)
at SimpleWorkerProtocol._handleMessage (:4200/editor.worker.bundle.js:6484)
at SimpleWorkerProtocol.handleMessage (:4200/editor.worker.bundle.js:6457)
at SimpleWorkerServer.onmessage (:4200/editor.worker.bundle.js:6619)
at self.onmessage (:4200/editor.worker.bundle.js:10166)
the modified client and server goes like this:
client.ts
import { listen, MessageConnection } from 'vscode-ws-jsonrpc';
import * as monaco from 'monaco-editor'
import {
MonacoLanguageClient, CloseAction, ErrorAction,
MonacoServices, createConnection
} from 'monaco-languageclient';
import normalizeUrl = require('normalize-url');
const ReconnectingWebSocket = require('reconnecting-websocket');
// register Monaco languages
monaco.languages.register({
id: 'typescript',
extensions: ['.ts'],
aliases: ['TypeScript','ts','TS','Typescript','typescript']
})
// create Monaco editor
const value = `
let message:string = 'foo'
`;
monaco.editor.create(document.getElementById("container")!, {
model: monaco.editor.createModel(value, 'typescript', monaco.Uri.parse('file:///C:\\Users\\foo\\Desktop\\project\\demo\\ts\\file.ts')),
glyphMargin: true,
theme: "vs-dark",
lightbulb: {
enabled: true
}
});
// install Monaco language client services
MonacoServices.install(monaco)
// create the web socket
const url = createUrl('ws://localhost:3000/ws')
const webSocket = createWebSocket(url);
// listen when the web socket is opened
listen({
webSocket,
onConnection: connection => {
// create and start the language client
const languageClient = createLanguageClient(connection);
const disposable = languageClient.start();
connection.onClose(() => disposable.dispose());
}
});
function createLanguageClient(connection: MessageConnection): MonacoLanguageClient {
return new MonacoLanguageClient({
name: "Sample Language Client",
clientOptions: {
// use a language id as a document selector
documentSelector: ['typescript'],
// disable the default error handler
errorHandler: {
error: () => ErrorAction.Continue,
closed: () => CloseAction.DoNotRestart
}
},
// create a language client connection from the JSON RPC connection on demand
connectionProvider: {
get: (errorHandler, closeHandler) => {
return Promise.resolve(createConnection(connection, errorHandler, closeHandler))
}
}
});
}
function createUrl(path: string): string {
return normalizeUrl(path);
}
function createWebSocket(url: string): WebSocket {
const socketOptions = {
maxReconnectionDelay: 10000,
minReconnectionDelay: 1000,
reconnectionDelayGrowFactor: 1.3,
connectionTimeout: 10000,
maxRetries: Infinity,
debug: false
};
return new ReconnectingWebSocket(url, [], socketOptions);
}
server.ts
import * as express from "express";
const app = express();
app.use(express.static(__dirname));
app.listen(4200)

TypeError: Cannot read property 'type' of undefined (redux toolkit)

I'm trying to fetch some data with redux toolkit but it doesn't work. I just keep getting the error TypeError: Cannot read property 'type' of undefined. I set up the store correct because i have other reducer working fine. But when i tried the asyn or fetch data, i have this problem
Error:
App.js:
The code stop at const actionResult = await dispath(getLiveContest()) it doesn't console log anything after.
const dispatch = useDispatch();
useEffect(() => {
const fetchLiveContest = async () => {
try {
console.log(1);
const actionResult = await dispatch(getLiveContest());
console.log(2);
const liveContest = unwrapResult(actionResult);
console.log(liveContest);
} catch (error) {
console.log("Failed to fetch live contest: ", error);
}
};
fetchLiveContest();
}, []);
GetLiveContest():
Here is the code of the function. I tried to return {name: 'lala'} and it's still gave me the type error
export const getLiveContest = createAsyncThunk(
"contests/fetchLive",
async (params, thunkAPI) => {
console.log(thunkAPI, "thunkAPI");
console.log(params);
const liveContest = await axios ...
return liveContest;
}
);
Code of the slide:
export const liveContestSlide = createSlice({
name: "live",
initialState: {
contest: [],
loading: "idle",
},
reducers: {},
extraReducers: {
// Add reducers for additional action types here, and handle loading state as needed
[getLiveContest.fulfilled]: (state, action) => {
// Add contest to the state array
state.contest.push(action.payload);
},
},
});
I followed the redux toolkit doc. I also checkout other question on stackoverflow but still can't fix the error, pls help
I just change import getLiveContest from "./contestSlice"; to import { getLiveContest } from "./contestSlice"; and it work, turn out i just import the function wrong

how do I unit test this function which handles observables

I have created this function because for all the requests my application sends out using http.post, this is how different parts handle the response. So rather than duplicating the code, I thought to create a function. But I am unable to figure out how to unit test this function.
private editAnswerSubject: Subject<Result>;
subscribeToReturnedObservable(observable:Observable<any>, subject:Subject<Result>) {
observable.subscribe((res) => {
const ev = <HttpEvent<any>>(res);
if (ev.type === HttpEventType.Response) {
const isResponseStructureOK: boolean = this.helper.validateServerResponseStructure(ev.body);
if (isResponseStructureOK) {
const response: ServerResponseAPI = ev.body;
subject.next(new Result(response.result, response['additional-info']));
} else {
subject.next(new Result(messages.error, messages.invalidStructureOfResponse));
}
}
},
(error: ServerResponseAPI) => {
const errorMessage: string = this.helper.userFriendlyErrorMessage(error);
subject.next(new Result(messages.error, errorMessage));
},
() => { // observable complete
});
}
editAnswer(answer: Answer): any {
const observable = this.bs.editAnswer(answer)
this.subscribeToReturnedObservable(observable,this.editAnswerSubject);
}
The test I have written so far is
describe('subscribeToReturnedObservable tests:', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [QuestionManagementService, HelperService, WebToBackendInterfaceService, AuthService, HttpClient, HttpHandler]
});
});
fit('should call send next value for the subject is the response from the server is ok', () => {
const questionService:QuestionManagementService = TestBed.get(QuestionManagementService);
const body = {"result":"success", "additional-info":"some additional info"};
const receivedHttpEvent = new HttpResponse({body:body});
let observable = new Observable();
spyOn(observable,'subscribe').and.returnValue(receivedHttpEvent);
spyOn(questionService['editQuestionSubject'],'next');
questionService.subscribeToReturnedObservable(observable,questionService['editQuestionSubject']);
observable.subscribe();
expect(questionService['editQuestionSubject'].next).toHaveBeenCalled();
});
});
But it get error Expected spy next to have been called.
I did this (hoping that it is the right way). The scope of testing is to check that the Subject's next is called correctly. So create an Observable using of and let the code flow from there.
fit('should call send next value for the subject is the response from the server is ok', () => {
const questionService:QuestionManagementService = TestBed.get(QuestionManagementService);
const helperService:HelperService = TestBed.get(HelperService);
const body = {"result":"success", "additional-info":"some additional info"};
const receivedHttpEvent = new HttpResponse({body:body});
const expectedResult = new Result('success', 'some additional info');
spyOn(helperService,'validateServerResponseStructure').and.returnValue(true);
let observable = of(receivedHttpEvent);
spyOn(questionService['editQuestionSubject'],'next');
questionService.subscribeToReturnedObservable(observable,questionService['editQuestionSubject']);
expect(questionService['editQuestionSubject'].next).toHaveBeenCalledWith(expectedResult);
});

Resources