can't find variable function declaration react native - javascript

I get the error "variable uploadImageAsync cannot be found"
uploadImageAsync = async (uri) => {
console.log("In upload image asnyc!");
}
And this is where I call it from.
_handleImagePicked = async pickerResult => {
let uploadResponse, uploadResult;
this.setState({ uploading: true });
if (!pickerResult.cancelled) {
uploadResponse = await uploadImageAsync(pickerResult.uri);
uploadResult = await uploadResponse.json();
this.setState({ image: uploadResult.location });
}
this.setState({ uploading: false });
};
How can I get around this?
So far I've tried:
async function uploadImageAsync(uri) {
I've also tried:
async uploadImageAsync(uri) {

If the uploadImageAsync function defined in the same component, you need call this.uploadImageAsync.
Otherwise, you must import it from the other module
or define the function outside the component in the same file.

Related

How to set conditional onClick behaviour in react with async function

I have a button which sends an async request but I only want to send this if a variable is false. I have tried to follow this question but I keep getting errors
This is the original onClick
onClick={async () => {
const CompleteCA = async () => {
try {
if (!statusFinal) {
await sendTransaction({
},
});
}
await updateCA({
variables: {
id: CA,
},
});
history.push('/');
} catch (error) {
logError(error);
}
};
CompleteCA();
}}
After adding conditional:
onClick={async () => {
testFlag ? alert("flag is true") :
const CompleteCA = async () => {
try {
...... rest of function
}
};
CompleteCA();
}}
I'm getting all the lines underlined since const can't be declared inside onClick, but I'm not sure how to move this out to another function and keep the async intact
I would recommend defining the async function separately and putting the conditional logic in there. Then call it from the onClick like <button onClick={async () => { await asyncFunc(); } }>Click</button>
Here is a simple CodeSandbox example.

Mocked copyFile and stat function not getting called in jest

I am trying to mock copyFile and stat method from fs modules(fs.promises). But the mocked function is not being called and instead the original functions are called though the test cases pass.
The testing function code is:
jest.doMock('fs', () => ({
promises: {
copyFile: (src = 'source', dest = 'destination') =>
jest.fn().mockImplementation(async () => {
console.log('Inside the mock function in copyFile, please get executed, got frustrated', src, dest);
return Promise.resolve(false);
}),
stat: () =>
jest.fn().mockImplementation(async () => {
console.log('Inside the mock function in stat method, please get executed, got frustrated');
return Promise.resolve(false); // Probably wrong datatype
}),
},
}));
describe('Testing implementation', () => {
const sample = new MainFunction()
test('Testing', async () => {
expect(sample.demo()).toEqual(Promise.resolve(true));
});
});
Actual Code which needs to be tested:
import * as fs from 'fs';
export class MainFunction {
async demo(): Promise<any> {
const fileName = 'C:/Users/Desktop/testing-file-dir/';
const fileName1 = '/destination/'
let filefound = (await fs.promises.stat(fileName)).isFile();
await fs.promises.copyFile(fileName,fileName1);
console.log(filefound, 'inside actual code');
return Promise.resolve(true);
}
}
Can someone please help regarding where I am going wrong ? I had thought of using jest.mock but it was also giving error so I followed this link https://github.com/facebook/jest/issues/2567 which suggested to try doMock. If someone knows better way to handle this mock function, it would be great.
Thanks !
You can use jest.mock(moduleName, factory, options), and you didn't mock the method chain call correctly. You should use mockFn.mockReturnThis() to return this context to the caller.
E.g.
index.ts:
import * as fs from 'fs';
export class MainFunction {
async demo(): Promise<any> {
const fileName = 'C:/Users/Desktop/testing-file-dir/';
const fileName1 = '/destination/';
let filefound = (await fs.promises.stat(fileName)).isFile();
await fs.promises.copyFile(fileName, fileName1);
console.log(filefound, 'inside actual code');
return Promise.resolve(true);
}
}
index.test.ts
import { MainFunction } from './';
jest.mock('fs', () => ({
promises: {
copyFile: jest.fn().mockImplementation((src = 'source', dest = 'destination') => {
console.log('Inside the mock function in copyFile, please get executed, got frustrated', src, dest);
return Promise.resolve(false);
}),
stat: jest.fn().mockReturnThis(),
isFile: jest.fn().mockImplementation(() => {
console.log('Inside the mock function in stat method, please get executed, got frustrated');
return Promise.resolve(false);
}),
},
}));
describe('Testing implementation', () => {
const sample = new MainFunction();
test('Testing', async () => {
const actual = await sample.demo();
expect(actual).toBeTruthy();
});
});
test result:
PASS examples/66429093/index.test.ts
Testing implementation
✓ Testing (10 ms)
console.log
Inside the mock function in stat method, please get executed, got frustrated
at Object.<anonymous> (examples/66429093/index.test.ts:12:15)
console.log
Inside the mock function in copyFile, please get executed, got frustrated C:/Users/Desktop/testing-file-dir/ /destination/
at Object.<anonymous> (examples/66429093/index.test.ts:7:15)
console.log
Promise { false } inside actual code
at MainFunction.<anonymous> (examples/66429093/index.ts:9:13)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.12 s, estimated 4 s
Based upon slideshowp2's solution, I had to do this change in order to avoid the error as stated in this https://github.com/facebook/jest/issues/2567.
The actual file remains same while test file changes to:
jest.mock('fs', () => {
const originalModule = jest.requireActual('fs'); // so as to not override other functions apart from below mentioned one's
return Object.assign({ __esModule: true }, originalModule, {
promises: {
copyFile: jest.fn().mockImplementation((src, dest) => {
// src, dest are parameters passed in copyFile from src to destination
let source = 'some source'; // sample source file
if (source === src) {
return true;
} else {
throw Error;
}
}),
stat: jest.fn().mockReturnThis(),
isFile: jest
.fn()
.mockImplementationOnce(() => { // I had series of test so for first one I wanted false hence this part, else we can remove this and directly use .mockImplementation()
return false;
})
.mockImplementation(() => {
return true;
}),
},
});
});
describe('Testing implementation', () => {
const sample = new MainFunction();
test('Testing', async () => {
const actual = await sample.demo();
expect(actual).toBeTruthy();
});
});

How to solve an error 'cb is not a function' in React Native?

current code
Index.js
import Auth from 'app/src/common/Auth';
export default class Index extends React.Component {
async componentDidMount() {
this.props.navigation.addListener('willFocus',
Auth.me().then(async (response) => {
await this.setState({ isLoggedIn: response });
}));
}
...
}
Auth.js
import axios from 'axios';
import { ENV } from 'app/env';
import { AsyncStorage } from 'react-native';
const { baseApiUrl } = ENV;
export default {
async me() {
try {
let result = false;
let token = await AsyncStorage.getItem('token');
token = token.replace(/"/g, '');
const response = await axios.get(`${baseApiUrl}/api/auth/me`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (response.data) {
result = true;
}
return result;
} catch (error) {
console.log(error);
}
},
};
error
I keep getting this error.
TypeError: cb is not a function. (In 'cb(data)', 'cb' is an instance of Promise)
I would appreciate it if you could give me any advice.
Its hard to tell without detail knowledge of your code (or react), but from the name i would expect this.props.navigation.addListener to take a callback function. Instead you pass a promise.
this.props.navigation.addListener('willFocus',
Auth.me().then(async (response) => {
await this.setState({ isLoggedIn: response });
})
);
Try changing the code to:
this.props.navigation.addListener('willFocus', () => {
Auth.me().then(async (response) => {
await this.setState({ isLoggedIn: response });
})
});
EDIT: #kai answer is better (and correct) for the current problem. I will leave the answer though, using async/await on the setState function is wrong anyway
You should remove the await from setState:
this.props.navigation.addListener('willFocus',
Auth.me()
.then((response) => {
this.setState({ isLoggedIn: response });
})
);
By using await, Javascript expects a Promise. But this.setState does not return a function.
On a sidenote, if you need to await for a setState function to be applied, you could use the callback as second parameter:
this.setState({ data }, () => console.log("Now the new state has been applied!"))
I resolved the same error by removing the listener from componentDidMount method
//this.props.navigation.addListener('focus', this._onFocus);

How to get the data from a async function and used that as a property value for a json on another asyn function?

Hi I'm new in using nodejs and haven't used javascript for a long time but i'm having a hard time getting a data from async function since I'm not getting any data when i try to use that to another async function, how would i do this without me causing so much confusion inside my project. Thank you in advance.
router
//this function is located inside a router and i want to use the output as a property value for a json.
const createPaymentMethod = async () => {
return paymongo.paymentMethods.create({
data: {
attributes: {
type: 'card',
details: {
card_number: card,
exp_month: mo,
exp_year: yr,
cvc: cvc,
}
}
}
},
)
.then(paymentMethods => {
return paymentMethods.data.id;
})
.catch(err => {
return err;
});
}
const getPaymentMethodId = async () => {
var id = await createPaymentMethod();
console.log(id);
}
//Attaching Payment Method to Intent
const attachPaymentIntent = async () => {
return paymongo.paymentIntents.attach(getPaymentIntentId(),{
data: {
attributes: {
payment_method: getPaymentMethodId()
}
}
})
.then(attachPaymentIntent => {
return attachPaymentIntent;
})
.catch(err => {
return err;
});
}
const getAttachedPaymentIntent = async () => {
var id = await attachPaymentIntent();
console.log(id);
}
getAttachedPaymentIntent();
//but after all this trouble the API still saying that the 'payment_method:' inside the attachPaymentIntent is still empty.
Since your getPaymentMethodId() is an async function. You have to use await operator to wait for its promise.
const payment_method = await getPaymentMethodId();
payment_method: payment_method;

Async function in Node js doesn't call the function that is suppose to be Called After its execution

I am working on a project where I need to use electron js (I am new to javascript). When I tried to use the electron.remote.dialog.showOpenDialog function, it does not call the function that is supposed to execute after async functions execution (console.log). The Sync method was successful and the Async is not. If someone can help please help me.
Here is the code.
Async method (unsuccessful)
const { dialog } = require("electron").remote;
dirButton = document.getElementById('select-file')
function getDir(e) {
dialog.showOpenDialog(
{ properties: ["openDirectory", "openFile"] },
console.log
);
}
dirButton.addEventListener("click", getDir);
Sync method (successful)
const { dialog } = require("electron").remote;
dirButton = document.getElementById('select-file')
function getDir(e) {
dirr = dialog.showOpenDialogSync(
{ properties: ["openDirectory", "openFile"] },
);
console.log(dirr)
}
dirButton.addEventListener("click", getDir);
You need to do something like this in Async call because it returns promise.
function getDir(e) {
dialog.showOpenDialog({ properties: ["openDirectory", "openFile"] }).
then(result => {
console.log(result)
}).catch(err => {
console.log(err)
})
}
Your Async method should be like this
const { dialog } = require("electron").remote;
dirButton = document.getElementById('select-file')
const getDir = async (e) => {
const dirr = await dialog.showOpenDialog({ properties: ["openDirectory", "openFile"] });
console.log(dirr);
}
dirButton.addEventListener("click", getDir);

Categories