I'm following the course of 32 hours Learn Blockchain, Solidity, .. in Javascript and I'm stucked with an error that others have but they solve because typos ecc.
I'm pretty sure at this point that the problem is not there but so what is the problem? I have my configuration file:
namedAccounts: {
deployer: {
default: 0,
1:0, // I even with this but nothing change
},
},
And I'm running everything in the hardhat default network, and when from the 00-deploy-mock.js the script calls the function getNamedAccounts():
module.exports = async function ({getNamedAccounts,deployments}){
const {deploy,log} = deployments
const {deployer} = await getNamedAccounts()
log(deployer)
if(developmentChains.includes(network.name)){
log("Local network " + network.name +" deploying mocks....")
await deploy("VRFCoordinatorV2Mock",{
from: deployer,
log: true,
args: [BASE_FEE,GAS_PRICE_LINK]
})
log("Mocks deployed !")
log("--------------------------------------------------")
}
}
log(deployer) prints undefined. and It returns the error:
TypeError: Cannot read properties of undefined (reading 'length')
The same process but using ganache instead run fine.
I have the hardhat-deploy plugin installed and i'm using the command hardhat deploy.
Any ideas ?
const { ethers } = require("hardhat");
async function main() {
const AMOUNT = ethers.utils.parseEther("0.1"); //bignumber
const [deployer] = await ethers.getSigners();
const iWTH = await ethers.getContractAt(
"IWeth",
"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
deployer
);
const tx = await iWTH.deposit({ value: AMOUNT });
await tx.wait(1);
const wethBalance = await iWTH.balanceOf(deployer.address);
console.log(`WETH OF ${deployer.address}:= WETH ${wethBalance / 10 ** 18} `);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
Try this this worked for me .instead of getNamedAccounts use
const [deployer] = await ethers.getSigners();
It's clear that deployer is not loaded properly.
This usually happens when you have not set up your module.exports in the file where you wrote the "getNamedAccounts()" function
in your hardhat-config.js file under the module.exports section please include the following feilds
namedAccounts: {
deployer: {
default: 0,
1: 0,
} } ,
also please ensure that the following imports are there
require("#nomiclabs/hardhat-waffle")
require("hardhat-gas-reporter")
require("#nomiclabs/hardhat-etherscan")
require("dotenv").config()
require("solidity-coverage")
require("hardhat-deploy")
although gas-reports and all are not necessary since you are fallowing the 31-hours course ....sooner or later you will be needing it
I guess it should work now
In Hardhat.config.js file
change getNamedAccounts to namedAccounts
namedAccounts: {
deployer: {
default: 0,
},
users: {
default: 1,
},
},
Also,
in deploy.js Make getNamedAccounts a function by adding
"()"
const { deployer } = await getNamedAccounts;
to
const { deployer } = await getNamedAccounts();
Code:
const { EmbedBuilder } = require("discord.js");
const got = require("got");
module.exports = {
name: "meme",
description: "Shows an image of a meme!",
run: async (client, message, args) => {
got("https://www.reddit.com/r/memes/random/.json").then(response => {
const [list] = JSON.parse(response.body);
const [post] = list.data.children;
const permalink = post.data.permalink;
const memeUrl = `https://reddit.com${post.data.permalink}`;
const memeImage = post.data.url;
const memeTitle = post.data.title;
const memeUpvotes = post.data.ups;
const memeNumComments = post.data.num_comments;
const memeEmbed = new EmbedBuilder()
.setTitle(`${memeTitle}`)
.setURL(`${memeUrl}`)
.setColor("Random")
.setImage(memeImage)
.setFooter({ text: `👍 ${memeUpvotes} | 💬 ${memeNumComments}` });
message.reply({ embeds: [memeEmbed] });
});
}
};
Error:
const got = require("got");
^
Error [ERR_REQUIRE_ESM]: require() of ES Module
/app/node_modules/got/dist/source/index.js from /app/commands/Image/meme.js not supported.
I’m not too sure what this ESM is, I’ve never dealt with it before, therefore I don’t know what to do to fix this.
Kinda think it’s got to do something with the package itself, but like I said I’m clueless as I’ve never had this error before.
got is a native ESM and no longer provides a CommonJS export.
Use ESM
To use the latest version, you'll have to convert to ESM:
you need to add "type": "module" to your package.json
replace all require()s and module.exports with import and export
Downgrade got
Another option is to downgrade got to v11.8.3 as it's pretty stable:
You can run npm i got#11.8.3 in your console.
Here is the error that it is returning
Here is a picture of the error i'm getting when I run npm install puppeter
I found some stuff online with permissions, but this is about node_package space. It is not disk space as I've looked over my disk storage availability and there's plenty. Working on an Apify SDK, and I'm following the documentation, but the console is returning a whole bunch of error messages.
Can someone please help?
const Apify = require('apify')
Apify.main(async () => {
const requestQueue = await Apify.openRequestQueue();
await requestQueue.addRequest({ url: 'https://www.iana.org/' });
const crawler = new Apify.PuppeteerCrawler({
requestQueue,
handlePageFunction: async ({ request, page }) => {
const title = await page.title();
console.log(`Title of ${request.url}: ${title}`);
await Apify.utils.enqueueLinks({
requestQueue,
page,
pseudoUrls: ['https://www.iana.org/[.*]'],
});
},
});
await crawler.run();
});
Native developers,
I really searched a lot but couldn't find anything that fits my needs.
I am new to react native and have a question.
I wonder how I can save user preferences of my app.
For example, I am displaying a dismissible badge on my screen -> user dismisses it -> how do I save this decision so the badge won't appear on every start again?
I thought about writing a .json file where all preferences are defined and read it on every start.
Is this a common way to realize it or is there any other solution.
Thank you very much
Updated Answer at February 2022
React native, officially deprecated the usage of its built-in AsyncStorage. The latest solution is to install the community package of it.
# Install via NPM
npm install --save #react-native-async-storage/async-storage
# ...or install via YARN
yarn add #react-native-async-storage/async-storage
# ...or install via EXPO
expo install #react-native-async-storage/async-storage
And the implementation is like this
import AsyncStorage from '#react-native-async-storage/async-storage';
const storeKey = '#storage_Key'
const storeData = async (value) => {
try {
await AsyncStorage.setItem(storeKey, value)
} catch (e) {
// saving error
}
}
const getData = async () => {
try {
const value = await AsyncStorage.getItem(storeKey)
if(value !== null) {
// value previously stored
}
} catch(e) {
// error reading value
}
}
deprecated doc: https://reactnative.dev/docs/asyncstorage
async storage doc: https://react-native-async-storage.github.io/async-storage/docs/install/
Consider another options: https://reactnative.directory/?search=storage
Old Answer
There are so many options out there, but the most common you can use is the React Native built-in AsyncStorage.
Sample Code
import { AsyncStorage } from "react-native";
const storeKey = 'myPreference';
storeData = async () => {
try {
await AsyncStorage.setItem(storeKey, 'I like to save it.');
} catch (error) {
// Error saving data
}
}
retrieveData = async () => {
try {
const value = await AsyncStorage.getItem(storeKey);
if (value !== null) {
// We have data!!
console.log(value);
}
} catch (error) {
// Error retrieving data
}
}
read more at https://facebook.github.io/react-native/docs/asyncstorage.html
Or you could reconsider 3rd party library like:
https://github.com/kevinresol/react-native-default-preference
https://github.com/mCodex/react-native-sensitive-info
I have this error when I compile my code in node.js, how can I fix it?
RefernceError: fetch is not defined
This is the function I am doing, it is responsible for recovering information from a specific movie database.
function getMovieTitles(substr){
pageNumber=1;
let url = 'https://jsonmock.hackerrank.com/api/movies/search/?Title=' + substr + "&page=" + pageNumber;
fetch(url).then((resp) => resp.json()).then(function(data) {
let movies = data.data;
let totPages = data.total_pages;
let sortArray = [];
for(let i=0; i<movies.length;i++){
sortArray.push(data.data[i].Title);
}
for(let i=2; i<=totPages; i++){
let newPage = i;
let url1 = 'https://jsonmock.hackerrank.com/api/movies/search/?Title=' + substr + "&page=" + newPage;
fetch(url1).then(function(response) {
var contentType = response.headers.get("content-type");
if(contentType && contentType.indexOf("application/json") !== -1) {
return response.json().then(function(json) {
//console.log(json); //uncomment this console.log to see the JSON data.
for(let i=0; i<json.data.length;i++){
sortArray.push(json.data[i].Title);
}
if(i==totPages)console.log(sortArray.sort());
});
} else {
console.log("Oops, we haven't got JSON!");
}
});
}
})
.catch(function(error) {
console.log(error);
});
}
If you're using a version of Node prior to 18, the fetch API is not implemented out-of-the-box and you'll need to use an external module for that, like node-fetch.
Install it in your Node application like this
npm install node-fetch
then put the line below at the top of the files where you are using the fetch API:
import fetch from "node-fetch";
This is a quick dirty fix, please try to eliminate this usage in production code.
If fetch has to be accessible with a global scope
import fetch from 'node-fetch'
globalThis.fetch = fetch
You can use cross-fetch from #lquixada
Platform agnostic: browsers, node or react native
Install
npm install --save cross-fetch
Usage
With promises:
import fetch from 'cross-fetch';
// Or just: import 'cross-fetch/polyfill';
fetch('//api.github.com/users/lquixada')
.then(res => {
if (res.status >= 400) {
throw new Error("Bad response from server");
}
return res.json();
})
.then(user => {
console.log(user);
})
.catch(err => {
console.error(err);
});
With async/await:
import fetch from 'cross-fetch';
// Or just: import 'cross-fetch/polyfill';
(async () => {
try {
const res = await fetch('//api.github.com/users/lquixada');
if (res.status >= 400) {
throw new Error("Bad response from server");
}
const user = await res.json();
console.log(user);
} catch (err) {
console.error(err);
}
})();
If you want to avoid npm install and not running in browser, you can also use nodejs https module;
const https = require('https')
const url = "https://jsonmock.hackerrank.com/api/movies";
https.get(url, res => {
let data = '';
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
data = JSON.parse(data);
console.log(data);
})
}).on('error', err => {
console.log(err.message);
})
fetch came to Node v17 under experimental flag --experimental-fetch
It will be available in Node v18 without the flag.
https://github.com/nodejs/node/pull/41749#issue-1118239565
You no longer need any additional package to be installed
EDITED - New Solution
To use the latest version (3.0.0) you must do the import like this:
const fetch = (url) => import('node-fetch').then(({default: fetch}) => fetch(url));
Old Anwser:
This may not be the best solution, but if you install this version :
npm install node-fetch#1.7.3
you can now use the line below without error's.
const fetch = require("node-fetch");
Node.js hasn't implemented the fetch() method, but you can use one of the external modules of this fantastic execution environment for JavaScript.
In one of the other answers, "node-fetch" is cited and that's a good choice.
In your project folder (the directory where you have the .js scripts) install that module with the command:
npm i node-fetch --save
Then use it as a constant in the script you want to execute with Node.js, something like this:
const fetch = require("node-fetch");
You should add this import in your file:
import * as fetch from 'node-fetch';
And then, run this code to add the node-fetch:
$ yarn add node-fetch
If you're working with typescript, then install node-fetch types:
$ yarn add #types/node-fetch
Best one is Axios library for fetching.
use npm i --save axios for installng and use it like fetch, just write axios instead of fetch and then get response in then().
You have to use the isomorphic-fetch module to your Node project because Node does not contain Fetch API yet. For fixing this problem run below command:
npm install --save isomorphic-fetch es6-promise
After installation use below code in your project:
import "isomorphic-fetch"
For those also using typescript on node-js and are getting a ReferenceError: fetch is not defined error
npm install these packages:
"amazon-cognito-identity-js": "3.0.11"
"node-fetch": "^2.3.0"
Then include:
import Global = NodeJS.Global;
export interface GlobalWithCognitoFix extends Global {
fetch: any
}
declare const global: GlobalWithCognitoFix;
global.fetch = require('node-fetch');
It seems fetch support URL scheme with "http" or "https" for CORS request.
Install node fetch library npm install node-fetch, read the file and parse to json.
const fs = require('fs')
const readJson = filename => {
return new Promise((resolve, reject) => {
if (filename.toLowerCase().endsWith(".json")) {
fs.readFile(filename, (err, data) => {
if (err) {
reject(err)
return
}
resolve(JSON.parse(data))
})
}
else {
reject(new Error("Invalid filetype, <*.json> required."))
return
}
})
}
// usage
const filename = "../data.json"
readJson(filename).then(data => console.log(data)).catch(err => console.log(err.message))
In node.js you can use : node-fetch package
npm i node-fetch
then :
import fetch from 'node-fetch';
here is a full sample in (nodejs) :
import fetch from "node-fetch";
const fetchData = async () => {
const res = await fetch("https://restcountries.eu/rest/v2/alpha/col"); // fetch() returns a promise, so we need to wait for it
const country = await res.json(); // res is now only an HTTP response, so we need to call res.json()
console.log(country); // Columbia's data will be logged to the dev console
};
fetchData();
In HackerRank, some libraries are installed by default and some are not.
Because it is running Node.js, the fetch API is not installed by default.
The best thing for you to do is to check whether the libraries are or not installed.
on the top of the exercise, there is the following:
const https = require('https');
Please try to add this to the top as well:
const axios = require('axios');
and then run the code.
If there is a compilation error, then it's not available, otherwise you can use axios, which is a good alternative to fetch
To use it with then, you can:
function getMovieTitles(substr){
axios.get(url)
.then(function(response){
console.log(response.data);
})
}
or taking advantage of the async/await
async function getMovieTitles(substr){
let response = await axios.get(url)
console.log(response.data);
}
This is the related github issue
This bug is related to the 2.0.0 version, you can solve it by simply upgrading to version 2.1.0.
You can run
npm i graphql-request#2.1.0-next.1
The following works for me in Node.js 12.x:
npm i node-fetch;
to initialize the Dropbox instance:
var Dropbox = require("dropbox").Dropbox;
var dbx = new Dropbox({
accessToken: <your access token>,
fetch: require("node-fetch")
});
to e.g. upload a content (an asynchronous method used in this case):
await dbx.filesUpload({
contents: <your content>,
path: <file path>
});
This worked for me:
const nodeFetch = require('node-fetch') as typeof fetch;
For me these are looking more simple.
npm install node-fetch
import fetch from "node-fetch";
There are actually a lot of different libraries for making fetch available in the browser.
The main ones I'm aware of are:
node-fetch
cross-fetch
whatwg-fetch
isomorphic-fetch
I currently use node-fetch, and it has worked fine, but I don't really know which one is "the best". (though the openbase.com pages I linked to provide some metadata on usage [eg. Github stars, npm downloads], which can help)
npm i node-fetch
Once installed, in your JavaScript file:
import fetch from "node-fetch";
Lastly make this change package.json file:
"type": "module"
Just make your app.js file Extension as app.mjs and the problem will be solved!!!:)
Solution without installations
Method 1
import { PLATFORM_ID } from '#angular/core';
import { isPlatformBrowser, isPlatformServer } from '#angular/common';
constructor(#Inject(PLATFORM_ID) private platformId: Object) {
// constructor code
}
ngOnInit() {
if (isPlatformBrowser(this.platformId)) {
// Client only code. Any javascript base functions
}
if (isPlatformServer(this.platformId)) {
// Server only code. Any javascript base functions
}
}
Method 2
import { PLATFORM_ID} from '#angular/core';
import { isPlatformBrowser } from '#angular/common';
#Component({
selector: 'app-navigation',
templateUrl: './navigation.component.html',
styleUrls: ['./navigation.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class NavigationComponent implements OnInit {
private isBrowser: boolean = false;
constructor(
#Inject(PLATFORM_ID) private platformId: Object
) {
this.isBrowser = isPlatformBrowser(platformId);
}
ngOnInit(): void {
if (this.isBrowser) {
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then((response) => response.json())
.then((json) => console.log(json));
}
}
}
DEMO - JSFIDDLE - Open console to view the fetch api service working
This answer does not directly answer this question. Instead it suggests for an alternative.
Why? Because the using 'node-fetch' is getting complicated since you cannot import the updated versions using const fetch = require('node-fetch') . You will have to do more things to just make it work.
Try using axios package:
Simple installation npm i axios
code for fetching goes like
const response = await axios.get(url).then(res => res.data)
Might sound silly but I simply called npm i node-fetch --save in the wrong project. Make sure you are in the correct directory.
If need install:
npm install --save global-fetch
then
var fetch = require("node-fetch");