How can I make this function synchronous with Asyn/await - javascript

I'm trying to make this code to be synchronous but for some reason async/await doesn't work.. Im working in React-native with two differents modules. I want to see my geolocation in googleMaps but it gets me a error because the asynchronous stuff.
App is the root component, im importing getLocalitation function.
export default class App extends Component {
Appmetod = async () => {
const resp = await getLocalitation();
console.log('Appmetod: latitud: ' + resp.latitude);
Linking.openURL(`http://www.google.com/maps/place/-33.317597,-71.405500`);
}
render() {
return (
<View style={styles.container}>
<Button title="Click me" onPress={this.Appmetod } />
</View>
);
}
}
const getLocalitation = () =>{
console.log('DENTRO DE GetLocalitaion');
const geoOptions={
enableHighAccuracy: true,
timeOut: 10000
};
const coordenates = navigator.geolocation.getCurrentPosition( geoSucces,goFailure, geoOptions);
console.log('DESPUES DE COORDENATES');
return coordenates;
}
const geoSucces = (position) => {
console.log('DENTRO DE GEOSUCCEES');
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const coordenates={
latitude: latitude,
longitude: longitude
};
console.log('COORDENATES: ' + coordenates.latitude);
return coordenates;
}
const goFailure = (err) => {
console.log('Error en al geolocalizar: ' + err);
return null;
}
OUTPUT:
C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\Utilities\infoLog.js:16 Running application "geolocation" with appParams: {"rootTag":161}. __DEV__ === true, development-level warning are ON, performance optimizations are OFF
C:\Users\jnunez\React-Native\Proyects\geolocation\src\getLocalitation.js:2 DENTRO DE GetLocalitaion
C:\Users\jnunez\React-Native\Proyects\geolocation\src\getLocalitation.js:10 DESPUES DE COORDENATES
C:\Users\jnunez\React-Native\Proyects\geolocation\src\getLocalitation.js:16 DENTRO DE GEOSUCCEES
C:\Users\jnunez\React-Native\Proyects\geolocation\src\getLocalitation.js:26 COORDENATES: -32.92098393
C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\YellowBox\YellowBox.js:67 Possible Unhandled Promise Rejection (id: 0):
TypeError: Cannot read property 'latitude' of undefined
TypeError: Cannot read property 'latitude' of undefined
at _callee$ (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:1895:58)
at tryCatch (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:41538:19)
at Generator.invoke [as _invoke] (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:41713:24)
at Generator.prototype.<computed> [as next] (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:41581:23)
at tryCatch (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:41538:19)
at invoke (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:41614:22)
at blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:41624:15
at tryCallOne (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:45254:14)
at blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:45355:17
at blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:46233:21
console.warn # C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\YellowBox\YellowBox.js:67
onUnhandled # C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\Promise.js:45
onUnhandled # C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\promise\setimmediate\rejection-tracking.js:71
(anonymous) # C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:256
_callTimer # C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:152
callTimers # C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:414
__callFunction # C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:366
(anonymous) # C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:106
__guard # C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:314
callFunctionReturnFlushedQueue # C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:105
(anonymous) # debuggerWorker.js:80

await / async do not stop code being asynchronous.
They are tools which let you write non-asynchronous style code by managing promises.
You can only await a promise. getLocalitation does not return a promise.
See How do I convert an existing callback API to promises? to get a promise for navigator.geolocation.getCurrentPosition.

It is because you're using await keyword with a function that is not async
const resp = await getLocalitation();
You can either put an async before the () when defining getLocation or you can just remove await from const resp = await getLocalitation(), since you don't need to use await with something that does not return a promise.
In case you want to make getLocalitation async you do it like this
const getLocalitation = async () =>{
console.log('DENTRO DE GetLocalitaion');
const geoOptions={
enableHighAccuracy: true,
timeOut: 10000
};
const coordenates = navigator.geolocation.getCurrentPosition( geoSucces,goFailure, geoOptions);
console.log('DESPUES DE COORDENATES');
return coordenates;
}

Related

How to access data from the createServer() method

I have a mock server which serves some json data. The server works correctly, but how can I access the data via fetch/axios? I am using fetch to fetch from the endpoint http://localhost:6000/users.
const http = require('http');
const json = require('./users.json');
const port = 6000;
http.createServer((req, res) => {
if (req.url === '/users') {
// Test error
res.write(JSON.stringify(json)).end();
} else {
res.writeHead(404).end();
}
}).listen(port, () => console.log(`Mock server listening on port ${port}`))
const { data: usersData } = useFetch("http://localhost:6000/users")
Here is the hook
const [data, setData] = useState(null);
useEffect(() => {
const _fetch = async () => {
try {
const response = await fetch(url);
const json = await response.json();
setData(json);
} catch (err) {
console.log(err)
}
};
_fetch();
}, [url]);
return {
data,
};
};
export default useFetch;
I receive the below error message locally.
GET http://localhost:6000/users net::ERR_EMPTY_RESPONSE
useFetch.js?7d5b:38 TypeError: Failed to fetch
at _callee$ (useFetch.js?7d5b:22:1)
at tryCatch (runtime.js?96cf:63:1)
at Generator.invoke [as _invoke] (runtime.js?96cf:294:1)
at Generator.eval [as next] (runtime.js?96cf:119:1)
at asyncGeneratorStep (asyncToGenerator.js?dbc6:3:1)
at _next (asyncToGenerator.js?dbc6:25:1)
at eval (asyncToGenerator.js?dbc6:32:1)
at new Promise (<anonymous>)
at eval (asyncToGenerator.js?dbc6:21:1)
at _fetch (useFetch.js?7d5b:49:1)
```
const port = 6000;
useFetch("http://localhost:5500/users")
You're using two different port numbers, you should change one of them.

React Native Expo [Unhandled promise rejection: Error: Could not create asset.]

i'm trying to save a base64 image to mobile phone. in expo-media-library i get an unhandled promise error and it does not save image to gallery.
const handleLongPress = async () => {
console.log(qrName);
qrSVG.toDataURL((data) => {
setImageSource("data:image/png;base64," + data);
console.log("DATA: ", imageSource);
});
const base64Code = imageSource.split("data:image/png;base64,")[1];
const filename = FileSystem.documentDirectory + qrName + ".png";
await FileSystem.writeAsStringAsync(filename, base64Code, {
encoding: FileSystem.EncodingType.Base64,
});
const mediaResult = await MediaLibrary.saveToLibraryAsync(filename);
console.log("Result: ", mediaResult);
};
FileSystem.writeasync() works correctly but when it's in the MediaLibrary.saveToLibraryAsync() it sends an unhandled promise error. Here is the Error:
[Unhandled promise rejection: Error: Could not create asset.]at node_modules\react-native\Libraries\BatchedBridge\NativeModules.js:106:50 in promiseMethodWrapper
at node_modules\expo-modules-core\build\NativeModulesProxy.native.js:15:23 in moduleName.methodInfo.name
at node_modules\expo-media-library\build\MediaLibrary.js:164:7 in saveToLibraryAsync
at node_modules\regenerator-runtime\runtime.js:63:36 in tryCatch
at node_modules\regenerator-runtime\runtime.js:294:29 in invoke
at node_modules\regenerator-runtime\runtime.js:63:36 in tryCatch
at node_modules\regenerator-runtime\runtime.js:155:27 in invoke
at node_modules\regenerator-runtime\runtime.js:190:16 in PromiseImpl$argument_0
at node_modules\react-native\node_modules\promise\setimmediate\core.js:45:6 in tryCallTwo
at node_modules\react-native\node_modules\promise\setimmediate\core.js:200:22 in doResolve
at node_modules\react-native\node_modules\promise\setimmediate\core.js:66:11 in Promise
at node_modules\regenerator-runtime\runtime.js:189:15 in callInvokeWithMethodAndArg
at node_modules\regenerator-runtime\runtime.js:212:38 in enqueue
at node_modules\regenerator-runtime\runtime.js:239:8 in exports.async
at node_modules\expo-media-library\build\MediaLibrary.js:141:7 in createAssetAsync
at node_modules\regenerator-runtime\runtime.js:63:36 in tryCatch
at node_modules\regenerator-runtime\runtime.js:294:29 in invoke
at node_modules\regenerator-runtime\runtime.js:63:36 in tryCatch
at node_modules\regenerator-runtime\runtime.js:155:27 in invoke
at node_modules\regenerator-runtime\runtime.js:165:18 in PromiseImpl.resolve.then$argument_0
at node_modules\react-native\node_modules\promise\setimmediate\core.js:37:13 in tryCallOne
at node_modules\react-native\node_modules\promise\setimmediate\core.js:123:24 in setImmediate$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:248:12 in _allocateCallback$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:112:14 in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:166:14 in _callReactNativeMicrotasksPass
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:418:41 in callReactNativeMicrotasks
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:393:6 in __callReactNativeMicrotasks
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:135:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:370:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:134:4 in flushedQueue
const handleLongPress = async () => {
const qrImagesDirectory = FileSystem.documentDirectory + "qrImages/";
const fileName = qrName + ".png";
saveQRAsImage(qrImagesDirectory, fileName, imageSource);
};
const saveQRAsImage = async (qrImagesDirectory, fileName, imageSource) => {
//Get folder
const folder = await FileSystem.getInfoAsync(qrImagesDirectory);
// Check if folder does not exist, create one furthermore
if (!folder.exists) {
await FileSystem.makeDirectoryAsync(qrImagesDirectory);
}
// Write file into the source of program
await FileSystem.writeAsStringAsync(
qrImagesDirectory + fileName,
imageSource,
{
encoding: FileSystem.EncodingType.Base64,
}
);
const ans = await FileSystem.getInfoAsync(qrImagesDirectory + fileName);
// Make the file accessible through mobile phone
FileSystem.getContentUriAsync(ans.uri).then((cUri) => {
//Open save image options
IntentLauncher.startActivityAsync("android.intent.action.VIEW", {
data: cUri,
flags: 1,
});
});
};
this worked for me!

Passing in list elements in javascript to a different function

I'm trying to do a web scraping exercise where some values are being retrieved and are being stored in a list variable. I am then passing in the list variable as a parameter in a different function. The problem with my approach is I am getting an error when calling the different function. I believe I'm getting this error because I am not passing in the list elements into the function appropriately. In the function, I am reading from a Yahoo Stock API used to retrieve stock data. If I were to hardcode a stock symbol into the parameter for the function, it works without any issue. Since I am passing in a parameter, I am getting this error. Below is my code and the error I am getting. Any feedback would be helpful.
Code
const cheerio = require('cheerio');
const axios = require('axios');
const yahooStockPrices = require('yahoo-stock-prices');
var stockSymbol = []
async function read_fortune_500() {
try {
const { data } = await axios({ method: "GET", url: "https://en.wikipedia.org/wiki/List_of_S%26P_500_companies", })
const $ = cheerio.load(data)
const elemSelector = '#constituents > tbody > tr > td:nth-child(1)'
$(elemSelector).each((parentIndex, parentElem) => {
let keyIndex = 0
if (parentIndex <= 9){
$(parentElem).children().each((childIndex, childElem) => {
const tdValue = $(childElem).text()
if (tdValue) {
//stockObject[keys[keyIndex]] = tdValue
stockSymbol = tdValue
}
})
console.log(stockSymbol)
}
})
} catch (err) {
console.error(err)
}
return stockSymbol;
}
async function collect_stocks(stockSymbol) {
stockSymbol = read_fortune_500()
const stockResult = await yahooStockPrices.getCurrentData(stockSymbol);
console.log(stockResult);
}
collect_stocks(stockSymbol)
Error
/node_modules/yahoo-stock-prices/yahoo-stock-prices.js:75
.split('regularMarketPrice')[1]
^
TypeError: Cannot read properties of undefined (reading 'split')
at Request._callback (/node_modules/yahoo-stock-prices/yahoo-stock-prices.js:75:21)
at Request.self.callback (/node_modules/request/request.js:185:22)
at Request.emit (node:events:390:28)
at Request.emit (node:domain:475:12)
at Request.<anonymous> (/node_modules/request/request.js:1154:10)
at Request.emit (node:events:390:28)
at Request.emit (node:domain:475:12)
at IncomingMessage.<anonymous> (/node_modules/request/request.js:1076:12)
at Object.onceWrapper (node:events:509:28)
at IncomingMessage.emit (node:events:402:35)
The parameter stockSymbol seems to be empty when you pass it to your desired function therefore, when yahoo-stock-prices try to apply a split on it, it fails.

Error: call revert exception (Flashloan with dydx, Uniswap and Kyber)

So I am trying to set up an Ethereum flashloan script on the Kovan test network, partly because of the great amount of funds needed to execute it on Mainnet.
I have therefore found all the Kovan addresses of the services used (dydx, kyber, the tokens to be exchanged etc.) and made a new key called ‘kovan’ with those addresses within the ‘addresses’ folder.
I then finally succeeded in deploying the contract on Kovan. And the websocket interaction of getting and displaying the blocks also works.
I expect it to be error-free while waiting for a transaction to go through. But every time it receives a new block, it gives me an error saying:
UnhandledPromiseRejectionWarning: Error: call revert exception (method="decimals()", errorSignature=null, errorArgs=[null], reason=null, code=CALL_EXCEPTION, version=abi/5.0.1)
This is the whole console log:
λ node run-arbitrage.js
{
kyber: { kyberNetworkProxy: '0x692f391bCc85cefCe8C237C01e1f636BbD70EA4D' },
uniswap: { router: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D' },
dydx: { solo: '0x4EC3570cADaAEE08Ae384779B0f3A45EF85289DE' },
tokens: {
dai: '0xc4375b7de8af5a38a93548eb8453a498222c4ff2',
usdc: '0xdcfab8057d08634279f8201b55d311c2a67897d2',
weth: '0xd0a1e359811322d97991e03f863a0c30c2cf029c'
}
}
web3-shh package will be deprecated in version 1.3.5 and will no longer be supported.
web3-bzz package will be deprecated in version 1.3.5 and will no longer be supported.
New block received. Block # 24267204
(node:20188) UnhandledPromiseRejectionWarning: Error: call revert exception (method="decimals()", errorSignature=null, errorArgs=[null], reason=null, code=CALL_EXCEPTION, version=abi/5.0.1)
at Logger.makeError (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\logger\lib\index.js:179:21)
at Logger.throwError (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\logger\lib\index.js:188:20)
at Interface.decodeFunctionResult (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\contracts\node_modules\#ethersproject\abi\lib\interface.js:286:23)
at Contract.<anonymous> (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\contracts\lib\index.js:300:56)
at step (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\contracts\lib\index.js:46:23)
at Object.next (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\contracts\lib\index.js:27:53)
at fulfilled (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\contracts\lib\index.js:18:58)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:20188) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:20188) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
And this is my run-arbitrage.js file:
require("dotenv").config()
const Web3 = require('web3');
const { ChainId, Token, TokenAmount, Pair } = require('#uniswap/sdk');
const abis = require('./abis');
const { kovan: addresses } = require('./addresses');
console.log(addresses)
const Flashloan = require('./build/contracts/Flashloan.json');
const web3 = new Web3(
new Web3.providers.WebsocketProvider(process.env.INFURA_KOVAN_URL)
);
const { address: admin } = web3.eth.accounts.wallet.add(process.env.PRIVATE_KEY);
const kyber = new web3.eth.Contract(
abis.kyber.kyberNetworkProxy,
addresses.kyber.kyberNetworkProxy
);
const ONE_WEI = web3.utils.toBN(web3.utils.toWei('1'));
const AMOUNT_DAI_WEI = web3.utils.toBN(web3.utils.toWei('20000'));
const DIRECTION = {
KYBER_TO_UNISWAP: 0,
UNISWAP_TO_KYBER: 1
};
const init = async () => {
const networkId = await web3.eth.net.getId();
const flashloan = new web3.eth.Contract(
Flashloan.abi,
Flashloan.networks[networkId].address
);
let ethPrice;
const updateEthPrice = async () => {
const results = await kyber
.methods
.getExpectedRate(
'0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
addresses.tokens.dai,
1
)
.call();
ethPrice = web3.utils.toBN('1').mul(web3.utils.toBN(results.expectedRate)).div(ONE_WEI);
}
await updateEthPrice();
setInterval(updateEthPrice, 15000);
web3.eth.subscribe('newBlockHeaders')
.on('data', async block => {
console.log(`New block received. Block # ${block.number}`);
const [dai, weth] = await Promise.all(
[addresses.tokens.dai, addresses.tokens.weth].map(tokenAddress => (
Token.fetchData(
ChainId.MAINNET,
tokenAddress,
)
)));
const daiWeth = await Pair.fetchData(
dai,
weth,
);
const amountsEth = await Promise.all([
kyber
.methods
.getExpectedRate(
addresses.tokens.dai,
'0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
AMOUNT_DAI_WEI
)
.call(),
daiWeth.getOutputAmount(new TokenAmount(dai, AMOUNT_DAI_WEI)),
]);
const ethFromKyber = AMOUNT_DAI_WEI.mul(web3.utils.toBN(amountsEth[0].expectedRate)).div(ONE_WEI);
const ethFromUniswap = web3.utils.toBN(amountsEth[1][0].raw.toString());
const amountsDai = await Promise.all([
kyber
.methods
.getExpectedRate(
'0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
addresses.tokens.dai,
ethFromUniswap.toString()
)
.call(),
daiWeth.getOutputAmount(new TokenAmount(weth, ethFromKyber.toString())),
]);
const daiFromKyber = ethFromUniswap.mul(web3.utils.toBN(amountsDai[0].expectedRate)).div(ONE_WEI);
const daiFromUniswap = web3.utils.toBN(amountsDai[1][0].raw.toString());
console.log(`Kyber -> Uniswap. Dai input / output: ${web3.utils.fromWei(AMOUNT_DAI_WEI.toString())} / ${web3.utils.fromWei(daiFromUniswap.toString())}`);
console.log(`Uniswap -> Kyber. Dai input / output: ${web3.utils.fromWei(AMOUNT_DAI_WEI.toString())} / ${web3.utils.fromWei(daiFromKyber.toString())}`);
if(daiFromUniswap.gt(AMOUNT_DAI_WEI)) {
const tx = flashloan.methods.initiateFlashloan(
addresses.dydx.solo,
addresses.tokens.dai,
AMOUNT_DAI_WEI,
DIRECTION.KYBER_TO_UNISWAP
);
const [gasPrice, gasCost] = await Promise.all([
web3.eth.getGasPrice(),
tx.estimateGas({from: admin}),
]);
const txCost = web3.utils.toBN(gasCost).mul(web3.utils.toBN(gasPrice)).mul(ethPrice);
const profit = daiFromUniswap.sub(AMOUNT_DAI_WEI).sub(txCost);
if(profit > 0) {
console.log('Arb opportunity found Kyber -> Uniswap!');
console.log(`Expected profit: ${web3.utils.fromWei(profit)} Dai`);
const data = tx.encodeABI();
const txData = {
from: admin,
to: flashloan.options.address,
data,
gas: gasCost,
gasPrice
};
const receipt = await web3.eth.sendTransaction(txData);
console.log(`Transaction hash: ${receipt.transactionHash}`);
}
}
if(daiFromKyber.gt(AMOUNT_DAI_WEI)) {
const tx = flashloan.methods.initiateFlashloan(
addresses.dydx.solo,
addresses.tokens.dai,
AMOUNT_DAI_WEI,
DIRECTION.UNISWAP_TO_KYBER
);
const [gasPrice, gasCost] = await Promise.all([
web3.eth.getGasPrice(),
tx.estimateGas({from: admin}),
]);
const txCost = web3.utils.toBN(gasCost).mul(web3.utils.toBN(gasPrice)).mul(ethPrice);
const profit = daiFromKyber.sub(AMOUNT_DAI_WEI).sub(txCost);
if(profit > 0) {
console.log('Arb opportunity found Uniswap -> Kyber!');
console.log(`Expected profit: ${web3.utils.fromWei(profit)} Dai`);
const data = tx.encodeABI();
const txData = {
from: admin,
to: flashloan.options.address,
data,
gas: gasCost,
gasPrice
};
const receipt = await web3.eth.sendTransaction(txData);
console.log(`Transaction hash: ${receipt.transactionHash}`);
}
}
})
.on('error', error => {
console.log(error);
});
}
init();

Calling async method from instanced Object gives error: TypeError: Object(...) is not a function

I am currently developing an app for educational purposes and facing a problem that is probably trivial but can't get around and solve it.
So basically I am trying to fetch some data from an external API (using Axios for that). I have divided my code into modules that I am exporting to index.js file and from that, I am instancing new Object and calling my async method getResults() which in return should give me data from API. From that point a get error
TypeError: Object(...) is not a function.
Here is an example code:
Module Search.js:
export default class Search {
constructor(query, num) {
this.query = query;
this.num = num;
}
async getResults() {
const url = 'API_URL';
const key = 'API_KEY';
try {
const res = await axios(`${url}?query=${this.query}&number=${this.num}&apiKey=${key}`);
this.result = res.data.results;
console.log(this.result);
} catch (error) {
console.log(error);
}
}
}
And here is index.js file:
import Search from "./models/Search";
const s = new Search('cheese', 2);
s.getResults()
And finally error in console:
TypeError: Object(...) is not a function
at Search._callee$ (Search.js:42)
at tryCatch (runtime.js:65)
at Generator.invoke [as _invoke] (runtime.js:303)
at Generator.prototype.<computed> [as next] (runtime.js:117)
at asyncGeneratorStep (Search.js:5)
at _next (Search.js:7)
at eval (Search.js:7)
at new Promise (<anonymous>)
at Search.eval (Search.js:7)
at Search.getResults (Search.js:65)
I am probably doing something wrong here, any help and insight would be appreciated. Thanks.
await axios(`${url}?query=${this.query}&number=${this.num}&apiKey=${key}`);
This is the line creating error,
axios is an object which you are trying to use as function
You probably wish to use get/post method provided by axios to call your endpoint
await axios.get(`${url}?query=${this.query}&number=${this.num}&apiKey=${key}`);
You can have a look how you want to use axios https://github.com/axios/axios

Categories

Resources