This is my vue.js function, it calls a python API . THe problem is around AWAIT
async getLinearSolver() {
const path = '/api/nutritional_constraints_1';
var vm = this
var json = await this.formatDataForPulp()
axios.post(path,json )
.then((res) => {
console.log(res)
vm.linear_result = "Write my res data "
})
.catch((error) => {
console.error(error);
});
}
console.log(res) is ok :
Object { data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, request: XMLHttpRequest }
but no template modification is possible, can't assign any variable to vm.linear_result
vm.linear_result = "Write my res data " is not working
:
[Vue warn]: Error in render: "Error: Cannot find module './undefined'"
found in
---> <NutritionalConstraints> at src/components/NutritionalConstraints.vue
<App> at src/App.vue
<Root> vue.runtime.esm.js:619
Error: Cannot find module './undefined'
webpackContextResolve .*$:51
webpackContext .*$:45
render NutritionalConstraints.vue:216
renderList VueJS
render NutritionalConstraints.vue:165
VueJS 14
_callee$/< NutritionalConstraints.vue:235
promise callback*_callee$ NutritionalConstraints.vue:220
Babel 11
onSubmit NutritionalConstraints.vue:290
VueJS 21
vue.runtime.esm.js:1888
Please help me, I really don't know what to do .
I have a similar query with no external AWAIT function, it works perfectly .
THis is a simplier example that leads to the same problem:
async getLinearSolver() {
const path = '/api/nutritional_constraints_1';
var vm = this
this.formatDataForPulp().then((res) => {
console.log(res) // Working
vm.a_template_variable ="Write my res data "// Not working !
})
}
Finally found out the problem .
I needed to deep clone some json array inside of my formatDataForPulp() function .
Like this :
var data = {
"items": JSON.parse(JSON.stringify(this.items)), // WE need to do a deep clone otherwize it crashes vue.js
"constraints": JSON.parse(JSON.stringify(this.constraints)) // WE need to do a deep clone otherwize it crashes vue.js
}
I was not doing it before, so vue.js was modifying my 2 way binding data during my formatDataForPulp() function, and then, vue.js was crashing !! THe problem was not coming from the ASYNC system.
Related
My application was working fine, then I updated it to react 18, now it is throwing "destroy is not a function" when I navigate from one route to another if the current route is using useEffect to call some APIs on load. I searched the internet in this regard but every question is not regarding this issue. maybe react 18 is new thats why i cant find a solution..
Though when i reload that same page it loads perfectly. its just when i navigate the application crashes.
And if i comment useEffect everything works fine
here is my useEffect Code
//on mount useEffect
useEffect(async () => {
getCases()
}, []);
//api calls functions ====>
//get cases function
const getCases = async () => {
const response = await Get(CASES.get, token);
setLoading(false);
if (!response.error) {
const { data } = response;
setCases(data);
console.log("fetched=======>", response);
} else {
setError(response.error);
console.log("error====>", response);
}
};
and this is the error im getting
Uncaught TypeError: destroy is not a function
at safelyCallDestroy (react-dom.development.js:22768:1)
at commitHookEffectListUnmount (react-dom.development.js:22932:1)
at commitPassiveUnmountInsideDeletedTreeOnFiber (react-dom.development.js:24874:1)
at commitPassiveUnmountEffectsInsideOfDeletedTree_begin (react-dom.development.js:24824:1)
at commitPassiveUnmountEffects_begin (react-dom.development.js:24732:1)
at commitPassiveUnmountEffects (react-dom.development.js:24717:1)
at flushPassiveEffectsImpl (react-dom.development.js:26847:1)
at flushPassiveEffects (react-dom.development.js:26801:1)
at commitRootImpl (react-dom.development.js:26752:1)
at commitRoot (react-dom.development.js:26517:1)
safelyCallDestroy # react-dom.development.js:22768
commitHookEffectListUnmount # react-dom.development.js:22932
commitPassiveUnmountInsideDeletedTreeOnFiber # react-dom.development.js:24874
commitPassiveUnmountEffectsInsideOfDeletedTree_begin # react-dom.development.js:24824
commitPassiveUnmountEffects_begin # react-dom.development.js:24732
commitPassiveUnmountEffects # react-dom.development.js:24717
flushPassiveEffectsImpl # react-dom.development.js:26847
flushPassiveEffects # react-dom.development.js:26801
commitRootImpl # react-dom.development.js:26752
commitRoot # react-dom.development.js:26517
performSyncWorkOnRoot # react-dom.development.js:25956
flushSyncCallbacks # react-dom.development.js:11982
(anonymous) # react-dom.development.js:25490
react_devtools_backend.js:3973 The above error occurred in the <Cases> component:
at Cases (http://localhost:3000/static/js/bundle.js:5474:77)
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
overrideMethod # react_devtools_backend.js:3973
logCapturedError # react-dom.development.js:18525
update.callback # react-dom.development.js:18558
callCallback # react-dom.development.js:13092
commitUpdateQueue # react-dom.development.js:13113
commitLayoutEffectOnFiber # react-dom.development.js:23204
commitLayoutMountEffects_complete # react-dom.development.js:24461
commitLayoutEffects_begin # react-dom.development.js:24447
commitLayoutEffects # react-dom.development.js:24385
commitRootImpl # react-dom.development.js:26651
commitRoot # react-dom.development.js:26517
performSyncWorkOnRoot # react-dom.development.js:25956
flushSyncCallbacks # react-dom.development.js:11982
(anonymous) # react-dom.development.js:25490
react-dom.development.js:22768 Uncaught TypeError: destroy is not a function
at safelyCallDestroy (react-dom.development.js:22768:1)
at commitHookEffectListUnmount (react-dom.development.js:22932:1)
at commitPassiveUnmountInsideDeletedTreeOnFiber (react-dom.development.js:24874:1)
at commitPassiveUnmountEffectsInsideOfDeletedTree_begin (react-dom.development.js:24824:1)
at commitPassiveUnmountEffects_begin (react-dom.development.js:24732:1)
at commitPassiveUnmountEffects (react-dom.development.js:24717:1)
at flushPassiveEffectsImpl (react-dom.development.js:26847:1)
at flushPassiveEffects (react-dom.development.js:26801:1)
at commitRootImpl (react-dom.development.js:26752:1)
at commitRoot (react-dom.development.js:26517:1)
Issue
The useEffect hook callback must be a synchronous function.
useEffect(async () => {
getCases()
}, []);
The async function implicitly returns a Promise object which is incorrectly interpreted by the React framework to be a returned cleanup function. This causes the error when the component is unmounting due to navigation.
Solution
There's no reason for the callback to be async, it's not calling any asynchronous code that it needs to await for. Remove the async keyword.
useEffect(() => {
getCases()
}, []);
For future reference if you need to use an async in the useEffect callback, define it locally in the callback and then invoke it.
useEffect(() => {
const asyncFn = async () => { .... };
asyncFn();
}, []);
Or externally like you did, keeping in mind that any linters may complain about a missing dependency.
Fixed it. removed async from useEffect and now it works fine.
//on mount useEffect
useEffect(() => {
getCases()
}, []);
//api calls functions ====>
//get cases function
const getCases = async () => {
const response = await Get(CASES.get, token);
setLoading(false);
if (!response.error) {
const { data } = response;
setCases(data);
console.log("fetched=======>", response);
} else {
setError(response.error);
console.log("error====>", response);
}
};
I use next.js middleware to retrieve a data stored inside a cookie, and to check in a db (using strapi) if this specific user exists, or if he needs to register before going further.
// middleware.js
import { getToken } from 'next-auth/jwt';
import qs from 'qs';
import { MY_DB } from './constants';
export async function middleware(request) {
const token = await getToken({
req: request,
secret: process.env.SECRET,
});
const params = qs.stringify({
filters: {
address: {
$eq: token.sub,
},
},
});
const url = MY_DB + '/api/users/?' + params;
const result = await fetch(url, {
method: 'GET',
headers: { accept: 'application/json' },
});
// remaining code checks if the request is empty or not and returns the appropriate page
(...)
building my project returns the following error :
Failed to compile.
./node_modules/.pnpm/function-bind#1.1.1/node_modules/function-bind/implementation.js
Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation
Import trace for requested module:
./node_modules/.pnpm/function-bind#1.1.1/node_modules/function-bind/implementation.js
./node_modules/.pnpm/function-bind#1.1.1/node_modules/function-bind/index.js
./node_modules/.pnpm/get-intrinsic#1.1.3/node_modules/get-intrinsic/index.js
./node_modules/.pnpm/side-channel#1.0.4/node_modules/side-channel/index.js
./node_modules/.pnpm/qs#6.11.0/node_modules/qs/lib/stringify.js
./node_modules/.pnpm/qs#6.11.0/node_modules/qs/lib/index.js
> Build failed because of webpack errors
ELIFECYCLE Command failed with exit code 1.
I highly suspect the qs.stringify call given the stacktrace, but how can I overcome this in an elegant way ?
I'm fighting with this issue for over 3 days. I have no idea what is happening.
Firebase Functions throws error only when I try to use Emulator. I try to execute this function in useEffect hook. Again, when I call deployed Cloud Functions everything seems fine, unfortunately in case of using Emulator things don't want to go so well.
const resolvePromise = async () => {
functions.useEmulator("https://0.0.0.0:5001");
const query = functions.httpsCallable("helloWorld");
query()
.then((result) => console.log(result))
.catch((err) => console.log(err));
};
I receive this useless (for me) error.
Error: ENOENT: no such file or directory, open 'HttpsErrorImpl#http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false'
at Object.openSync (node:fs:585:3)
at Object.readFileSync (node:fs:453:35)
at getCodeFrame (Z:\repo\PTCG_Marketplace\node_modules\metro\src\Server.js:1296:18)
at Z:\repo\PTCG_Marketplace\node_modules\metro\src\Server.js:1367:24
at Generator.next (<anonymous>)
at asyncGeneratorStep (Z:\repo\PTCG_Marketplace\node_modules\metro\src\Server.js:146:24)
at _next (Z:\repo\PTCG_Marketplace\node_modules\metro\src\Server.js:168:9)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
internal
at HttpsErrorImpl#http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:197178:29 in <unknown>
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:197273:29 in _errorForResponse
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:197751:39 in <unknown>
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:170357:26 in step
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:170287:21 in <unknown>
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:170241:31 in fulfilled
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:31526:15 in tryCallOne
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:31627:26 in <unknown>
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:31955:16 in _callTimer
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:31994:16 in _callImmediatesPass
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:32211:32 in callImmediates
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:3457:34 in __callImmediates
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:3236:33 in <unknown>
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:3440:14 in __guard
at http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false:3235:20 in flushedQueue
This is all the text which I can see after visiting
http://192.168.0.104:19000/index.bundle -- https://pastebin.com/ggsCMN0W
http://192.168.0.104:19000/index.bundle?platform=android&dev=true&hot=false&minify=false -- https://pastebin.com/LSeufs8H
It don't make any sense for me. At second address it seems like it's correlated to metro dependency so I updated it, it didn't work.
Any ideas? Thanks in advance :D
Edit 1: All errors are logged at client site, it seems like client can't even call emulator.
Edit 2:
I tried to update entire firebase to v.9 aswell as Expo to 44 SKD with react-native to 0.64.3
This is how my Request function looks now:
const requestApi = () => {
const functions = getFunctions(app);
connectFunctionsEmulator(functions, "127.0.0.1", 5001);
const helloWorld = httpsCallable(functions, "helloWorld");
helloWorld()
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error.message, error.code, error.details);
});
};
I receive only this from catch block :(
internal functions/internal undefined
I also receive warning about Timer after executing that function
Setting a timer for a long period of time, i.e. multiple minutes, is a
performance and correctness issue on Android as it keeps the timer
module awake, and timers can only be called when the app is in the
foreground. See https://github.com/facebook/react-native/issues/12981
for more info. (Saw setTimeout with duration 70000ms)
It don't work only when I try to use Emulator
Couple of potential issues here:
Assuming you're using the latest version of Firebase, functions is actually a method: firebase.functions().useEmulator("localhost", 5001); - Note the () after functions. See docs for more info.
Maybe you've already done this, but have you made sure that the functions emulator is actually running and connectable on port 5001)? Could be useful to test it via Postman or similar.
Make sure you're using the correct IP address for the functions emulator given your setup. 0.0.0.0 probably doesn't map where you want it to... assuming the app is running locally and the functions emulator is too, try 127.0.0.1 or "localhost" ... this answer has more options to troubleshoot.
I am not sure if it is your case, but I had a function:
exports.findUserInAuth = functions.https.onCall((data, context) => {
let field = data.field;
let value = data.value;
if (!field || !value) {
return false;
}
if (field === "email") {
return admin.auth().getUserByEmail(value);
}
});
This one returns a promise, I had to change it to wait for the result before doing a return and problem solved...
exports.findUserInAuth = functions.https.onCall((data, context) => {
let field = data.field;
let value = data.value;
if (!field || !value) {
return false;
}
if (field === "email") {
admin.auth().getUserByEmail(value).then((result) => {
return result;
})
.catch((error) => {
if (error.code === "auth/user-not-found") {
return "Email or Password is incorrect";
}
return `${error.code} ${error.message}`;
});
}
return false;
});
Ok, so after almost a week of fighting with this sh!t.
When you use Expo Go like me. You should copy the host address on which you are emulating your app, and use the same address you emulate your functions (or other tools).
app.json
{
"firestore": {
"rules": "firestore.rules",
"indexes": "firestore.indexes.json"
},
"emulators": {
"functions": {
"host": "192.168.0.104",
"port": 5001
}
}
}
and final code of requestApi function
const requestApi = async () => {
const functions = firebase.functions()
functions.useEmulator("192.168.0.104", 5001); <--- ADDRESS!!!
const helloWorld = functions.httpsCallable("helloWorld");
helloWorld()
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error.message, error.code, error.details);
});
};
I am trying to translate the name of a user from english to an indian language using google translate api and storing the data back in realtime database with a cloud function.
This function is invoked by a write to the database, and I am using a HTTP POST request to send a request to the cloud translate api and the response is stored back to the database. My code for the translate request is this.
var translate_options = { method: 'POST',
url: 'https://translation.googleapis.com/language/translate/v2',
qs:
{ key: 'key goes here',
},
form: {
q: fullData.name,
target: "te"
},
};
request(translate_options, function (error, translate_response, translate_body) {
if (error){
console.log("In translating, got an error");
console.log(error);
}
// Query to the database goes here.
});
This code, if tried in my laptop, gives me the correct translation, but if I deploy it as a cloud function, it gives me an error. Very specifically
{ Error: read ECONNRESET
at exports._errnoException (util.js:1020:11)
at TLSWrap.onread (net.js:568:26) code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }
I am on firebase blaze plan, and I am able to sent POST request to my other services, but not a google service.
Can anybody help me with this issue. Thanks in advance.
Edit :
The full code is
var functions = require('firebase-functions');
var admin = require('firebase-admin');
var request = require("request");
admin.initializeApp(functions.config().firebase);
exports.whenUserIsAdded = functions.database.ref('users/{companyId}/{uid}').onCreate(event => {
var fullData = event.data.val();
var lang_code = {
"bengali": "bn",
"telugu": "te",
"english": "en"
}
var lang_var = lang_code[fullData['edition']];
var translate_options = { method: 'POST',
url: 'https://translation.googleapis.com/language/translate/v2',
qs:
{ key: 'Key goes here',
},
form: {
q: fullData.name,
target: lang_var
},
};
request(translate_options, function (error, translate_response, translate_body) {
var farmer_name = "";
if(error){
console.log("There is an error in translation");
console.log(error);
}
translate_body = JSON.parse(translate_body);
if(translate_body.data.translations){
farmer_name = translate_body.data.translations[0].translatedText;
console.log("The farmer name is " + fullData.name +" : " + farmer_name);
// Code to write to the database;
} else{
console.log("The translation failed");
farmer_name = fullData.name;
console.log("The famrer name is " + farmer_name);
}
})
});
You're not returning a promise that's resolved when all the work of your function is complete. If the work was completing in the past, that possibly just means you were lucky. Without returning a promise, Cloud Functions may terminate and clean up any work that wasn't complete when the function returns. Properly returning a promise will prevent Cloud Functions from cleaning up before the work is done.
Please consider reading my blog post about this. There is a section special just for ECONNRESET.
I'm having difficulty invoking a login method, it follows
$ meteor list
Accounts-base 1.2.14 A user account system
Ecmascript 0.6.1 Compiler plugin that supports ES2015 + in all .js files
Meteor-base 1.0.4 Packages that every Meteor app needs
React 15.0.1 Everything you need to use React with Meteor.
Static-html 1.1.13 Defines static page content in .html files
/server/main.js
import { Accounts } from 'meteor/accounts-base'
Accounts.registerLoginHandler('simples', (ttt) => {
console.log(ttt);
});
/client/main.js
autenticar(){
Accounts.callLoginMethod({
methodName: 'simples',
methodArguments: [{ tipo : 'simples' }],
validateResult: function (result) {
console.log('result', result);
},
userCallback: function(error) {
if (error) {
console.log('error', error);
}
}
})
}
When calling authenticar(), I get this error:
errorClass
Details: undefined
Error: 404
ErrorType: "Meteor.Error"
Message: "Method 'simples' not found [404]"
Reason: "Method 'simples' not found"
Where is the error?
I've never used this API personally, but from a quick glance through the Meteor internals, I see a couple issues.
Accounts.registerLoginHandler only adds an additional handler to an array of built-in handlers which are called as part of the default Meteor login process.
If you are trying to plug in an additional handler into the existing process, you should call Accounts.callLoginMethod without the methodName key.
Calling Accounts.callLoginMethod with methodName will bypass the built-in handlers completely and replace them with your custom method, however this method needs to be declared separately by you with Meteor.methods, not registerLoginHandler.
So, that's probably your error -- you need to define your simples method with Meteor.methods. Also, you should check the code for the requirements of this method, see the comments in the code here:
https://github.com/meteor/meteor/blob/devel/packages/accounts-base/accounts_client.js
Only to complement and keep as a referral for someone else to get here. That way it's working
client.js
Accounts.callLoginMethod({
methodArguments: [{tipo: 'simples'}],
validateResult: (result) => {
console.log('success', result);
},
userCallback: function(error) {
if (error) {
console.log('error', error);
}
}
});
server.js
Meteor.startup(function () {
var config = Accounts.loginServiceConfiguration.findOne({
service : 'simples'
});
if (!config) {
Accounts.loginServiceConfiguration.insert({ service: 'simples' });
}
});
Accounts.registerLoginHandler((opts) => {
if(opts.tipo === 'simples'){
return Accounts.updateOrCreateUserFromExternalService ('simples', {
id: 0 // need define something
}, {
options : 'optional'
})
}
});