I'm setting the value of a global variable from a fetched value and I have it used all over the app.
When I first run the app using expo I get an error TypeError: undefined is not an object (evaluating 'global.value') but when I hit CMD+S on any page of the app the app get reloaded and everything works fine.
Here's the code of global.js:
var language = new Object();
var url = new Object();
module.exports = { language, url }
and here's how I set the values in App.js:
async checkServiceLevel(){
const response = await fetch(Config.backendAPI+`/service.php`);
const data = await response.json();
if(data['servicelevel'] === "up"){
global.url['url'] = Config.backendAPI;
}else{
const new_response = await fetch('https://backendrl0112.fra1.digitaloceanspaces.com/backendrl.json');
const new_data = await new_response.json();
global.url['url'] = new_data['url'];
}
}
async getLanguage(langue){
const response = await fetch(global.url['url']+`/getLanguageJson.php`);
const data = await response.json();
if(langue == null){
global.language['language'] = data['Languages']['en'];
await AsyncStorage.setItem('jsonLanguage',JSON.stringify(data['Languages']));
}else{
global.language['language'] = data['Languages'][langue];
await AsyncStorage.setItem('jsonLanguage',JSON.stringify(data['Languages']));
}
}
Here's the app behavior:
Related
I'm new to Puppeteer and trying to write an e2e test for a React app that enables logins using the GoogleLogin component from #react-oauth/google.
The code below works until the Google sign in window opens, but then I don't know how to access elements. I've looked at the element and I know that there's an input of type email, so I'd like to wait for that selector, but page doesn't seem to be the place to access it.
How do I move to the next step with this test?
const chalk = require( 'chalk' );
class LoginAccount {
constructor( page ) {
this.url = "http://localhost:3000"
this.page = page;
}
async login( username, password ) {
try {
const navigationPromise = page.waitForNavigation();
await this.page.goto( this.url );
const selector = '[role="button"]';
await this.page.waitForSelector( selector );
const button_handler = await page.$(selector);
await button_handler.evaluate(b => b.click());
await navigationPromise
const email_field = 'input[type="email"]'
await page.waitForSelector( email_field )
// Times out here
console.log("Got email input")
await this.page.type( email_field, username );
} catch ( err ) {
console.log( chalk.red( 'ERROR => ', err ) );
}
}
}
module.exports = ( page ) => new LoginAccount( page );
I was able to solve this. The browser.waitForTarget method gets me a handle to the new browser window that I need. The modified code below (starting just before the button click) works correctly:
const pageTarget = page.target();
await button_handler.evaluate(b => b.click());
const newTarget = await browser.waitForTarget(target => target.opener() === pageTarget);
const newPage = await newTarget.page();
const email_field = 'input[type="email"]'
await newPage.waitForSelector( email_field )
console.log("Got email input")
ive got a page which i call an api through getserversideprops to basically get all the data from a table. it used to work fine, but suddenly when i runned it today an error occured which i dont know the cause is. this is the response im getting when i console log the response
what i tried on my own and noticed to "help" was reducing the amount of columns that the API was selecting. For the api i used knex and express. this was the original code that used to work but now does not.
try{
let data = "";
await db.transaction(async (t)=>{
data = await db('sales').transacting(t)
.join('users','users.id','sales.cashier_id')
.join('customer','customer.customer_id','sales.customer_id')
.select('customer.name as customer_name','sales.sales_id','sales.date','sales.payment_type','sales.payment_status','sales.customer_id','sales.transaction_total','sales.total_paid','users.name','sales.shipment_fee','sales.days','sales.sale_type')
})
return data
}catch(e){
console.log(e);
throw e;
}
what i tried was reducing the amount of select columns to i think 5 or 6, but definitely if the amount of columsn i use is under a limit it works. like
try{
let data = "";
await db.transaction(async (t)=>{
data = await db('sales').transacting(t)
.join('users','users.id','sales.cashier_id')
.join('customer','customer.customer_id','sales.customer_id')
.select('customer.name as customer_name','sales.sales_id','sales.transaction_total','sales.date','sales.payment_type')
})
return data
}catch(e){
console.log(e);
throw e;
}
these are the attributes of my table
this is the server.js file of my expressjs
const compression = require('compression');
const express = require("express");
const app = express();
const fs = require('fs');
const http = require('http')
const https = require('https')
const PORT = process.env.PORT || 8000;
var cors = require('cors')
const mainRoutes = require('./api/v1/routes/index')
const cookieParser = require("cookie-parser");
app.use(compression());
app.use(cors( {origin: 'http://localhost:3000',credentials: true}))
// app.use(cors());
app.use(express.json());
// app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
// Main Routes
app.use("/api/v1", mainRoutes,(req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
this is how im calling the api from next
export async function getServerSideProps(context) {
try{
const res = await axios.get("/sales/get-all");
const data = await res.data
return { props: { data } }
}catch(err){
const data = "error"
return { props: { data} }
}
}
where i declared default url of the axios at the app.js file of next
import '../styles/globals.css'
import axios from 'axios';
axios.defaults.baseURL = "http://localhost:8000/api/v1/"
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp
im not quite sure what the problem is so pardon if the title of the question is not according to the problem i have.
EDIT:
i moved the api to a useeffect call, its now working. but why isnt it working in getserversideprops?
I was using ffmpeg.min.js through <script src='https://unpkg.com/#ffmpeg/ffmpeg#0.9.6/dist/ffmpeg.min.js'></script>
async function mergeVideo(video, audio) {
let { createFFmpeg, fetchFile } = FFmpeg;
let ffmpeg = createFFmpeg();
await ffmpeg.load();
ffmpeg.FS('writeFile', 'video.mp4', await fetchFile(video));
ffmpeg.FS('writeFile', 'audio.mp4', await fetchFile(audio));
await ffmpeg.run('-i', 'video.mp4', '-i', 'audio.mp4', '-c', 'copy', 'output.mp4');
let data = await ffmpeg.FS('readFile', 'output.mp4');
return new Uint8Array(data.buffer);
};
function saveVideo(fileName, byte) {
var blob = new Blob([byte], { type: "video/mp4" });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
};
mergeVideo("/videoplayback.webm", "/videoplayback2.webm").then(r => {
saveVideo("mergedVideo.mp4", r);
});
I was using above code for website but i am not getting how to do it in react native.
I did tried FFmpegKit its different there.
Can someone code similar to that in react native?
in my service worker i store mp4 video in indexedDB with localforage library in a blob data. It's work ! but i don't know how can i return this blob data.
This is my fetchHandler code :
const fetchHandler = async (event) => {
const getResponse = async () => {
const request = event.request;
if( request.destination === 'video' ){
// Get from indexedDB
const value = await localforage.getItem('video');
// How return the video from indexedDB cache ?
if( value ) return value; // not working
// Add in indexedDB
var networkResponse = await fetch(event.request);
localforage.setItem('video', networkResponse.blob() ).then(function (value) {
// Do other things once the value has been saved.
console.log(value);
}).catch(function(err) {
// This code runs if there were any errors
console.log(err);
});
}else{
const openedCache = await caches.open(SW_CACHE_NAME);
const cacheResponse = await openedCache.match(request);
if (cacheResponse) return cacheResponse;
var networkResponse = await fetch(event.request);
const cachePutResponse = await openedCache.put(request, networkResponse.clone());
if (cachePutResponse) return cachePutResponse;
}
return networkResponse;
};
event.respondWith(getResponse());
};
thanks for your help
You need to pass a valid Response object to event.respondWith(). That entails a response body (which is what you get back from localforeage.getItem()), but also some response headers.
You can use the Response constructor to create that, and return it from your getResponse() function.
The code could look something like:
const value = await localforage.getItem('video');
if (value) {
// See https://fetch.spec.whatwg.org/#bodyinit for what's accepted
// as a BodyInit.
return new Response(value, {
headers: {
// Replace this with the actual MIME type for the video.
'content-type': 'video/mp4',
// Include any other headers here if desired.
}
});
}
I use tensorflow-models/mobilenet for application Reat native of me.
The application works well when there is a network. But when the device is offline, on IOS applications it does not load model.
async function predictMobilenet() {
try {
setTextshow(' LOADING...')
var start = new Date().getTime();
console.log(' Load model...')
//const tfReady = await tf.ready();
const tfReady = await tf.ready();
console.log('Uffect load model')
const model = await mobilenet.load();
const imgB64 = await FileSystem.readAsStringAsync(selectedImage.localUri, {
encoding: FileSystem.EncodingType.Base64,
});
const imgBuffer = tf.util.encodeString(imgB64, 'base64').buffer;
const raw = new Uint8Array(imgBuffer)
const imageTensor = decodeJpeg(raw);
const prediction = await model.classify(imageTensor);
var end = new Date().getTime();
var time = end - start;
setTextshow(JSON.stringify(prediction))
setTime(time)
}catch (e) {
setTextshow(e.toString())
console.log(e)
}
}
code line: const model = await mobilenet.load(); not working on ios when device offline
Error on iOS:
error : network request failed.
But on Android, my application works well.