Type Error Cannot read properties of undefined (reading 'Web3Provider') at fetchingData - react-hooks

It must show console log Big Number instead its showing error.
expected output
error occured
I am new to blockchain. I have connected the private key of hardhat with wallet but its showing Type Error. The expected output and the output which Ive got has attached along with this.
import React, { useState, useEffect } from "react";
import { ethers, BigNumber } from "ethers";
import Web3Modal from "web3modal";
//INTERNAL IMPORT
import {
checkIfWalletConnected,
connectWallet,
connectingWithBooToken,
connectingWithLIfeToken,
connectingWithSingleSwapToken,
connectingWithIWTHToken,
connectingWithDAIToken,
} from "../Utils/appFeatures";
import { IWETHABI } from "./constants";
// import ERC20 from "./ERC20.json";
export const SwapTokenContext = React.createContext();
export const SwapTokenContextProvider = ({ children }) => {
const swap = "Welcome to swap my token";
//USESTATE
const [account, setAccount] = useState("");
const [ether, setEther] = useState("");
const [networkConnect, setNetworkConnect] = useState("");
const [weth9, setWeth9] = useState("");
const [dai, setDai] = useState("");
const [tokenData, setTokenData] = useState([]);
const addToken = [
"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
"0x15Ff10fCc8A1a50bFbE07847A22664801eA79E0f",
"0xAe9Ed85dE2670e3112590a2BB17b7283ddF44d9c",
];
//FETCH DATA
const fetchingData = async () => {
try{
//GET USER ACCOUNT
const userAccount = await checkIfWalletConnected();
setAccount(userAccount);
//CREATE PROVIDER
const web3modal = new Web3Modal();
const connection = await web3modal.connect();
const provider = new ethers.providers.Web3Provider(connection);
//CHECK Balance
const balance = await provider.getBalance(userAccount);
console.log(balance);
}catch(error){
console.log(error);
}
}
useEffect(()=>{
fetchingData();
},[]);
return (
<SwapTokenContext.Provider value={{swap}}>
{children}
</SwapTokenContext.Provider>
);
};

your imports are probably failed try to import like this instead :
const ethers = require("ethers");
const BigNumber = require("ethers");

Related

Upload image to server using expo-file-system

In a react native app, I am following the documentation of expo-file-system to upload an image from the gallery of my phone and send it to a node.js server that uses multer to process the file. Unfortunately, I am having the following error when I send the http request:
Possible Unhandled Promise Rejection (id: 1):
Error: Failed to connect to localhost/127.0.0.1:3000
I know that the server is working because I have tested it with the same client but using axios and fetch to send the request and it reached the server.
This is the code that I am using in the client side:
//.env
URL = 'http://localhost:3000/api/upload'
//uploadImage.js
import React, { useState } from "react";
import { View, Button, Image, StyleSheet } from "react-native";
import * as ImagePicker from 'expo-image-picker'
import * as FileSystem from 'expo-file-system';
import {URL} from "#env"
const ImageUpload = ()=>{
const [image, setImage] = useState('')
const [name, setName] = useState('')
const [type, setType] = useState('')
const openImageLibrary = async()=>{
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log('this is the result',result);
if (!result.canceled) {
const uri = result.assets[0].uri
const filename = uri.split('/').pop();
const match = /\.(\w+)$/.exec(filename);
const imageType = match ? `image/${match[1]}` : `image`;
setImage(uri);
setName(filename)
setType(imageType)
}
}
const sendPictureToServer = async()=>{
const response = await FileSystem.uploadAsync(URL ,image,{
fieldName: 'photo',
httpMethod: 'POST',
uploadType: FileSystem.FileSystemUploadType.BINARY_CONTENT,
})
}
return(
<View>
<Button title = 'select' onPress={openImageLibrary}/>
<Button title='send' onPress={sendPictureToServer}/>
</View>
)
}
This is the node.js server
//index.js
const Express = require('express')
const multer = require('multer')
const bodyParser = require('body-parser')
const app = Express()
app.use(bodyParser.json())
const upload = multer({ dest: 'uploads/' } )
app.get('/', (req, res) => {
res.status(200).send('You can post to /api/upload.')
})
app.post('/api/upload', upload.single('photo'), (req, res) => {
console.log('file', req.file)
console.log('body', req.body)
res.status(200).json({
message: 'success!',
})
})
app.listen(3000, () => {
console.log('App running on http://localhost:3000')
})

Dynamic axios request url in Vue 3 Composables

I've tried this and it worked:
const posts = ref{[]}
const urlEndPoint = 'posts'
const getPosts = async () => {
let response = await axios.get('/api/'+urlEndPoint)
posts.value = response.data.data
}
but that one is not dynamic. My goal is to make the urlEndPoint value reactive and set from the components
then i tried this:
const urlEndPoint = ref([])
but I don't know how to send the value of urlEndPoint constant back from the component to the composables.
I tried these in my component:
const urlEndPoint = 'posts'
and
const sendUrlEndPoint = () => {
urlEndPoint = 'posts'
}
but none worked.
is there a way to accomplish this goal? like sending the component name to urlEndPoint value in composable or any other simple way.
Define a composable function named use useFetch :
import {ref} from 'vue'
export default useFetch(){
const data=ref([])
const getData = async (urlEndPoint) => {
let response = await axios.get('/api/'+urlEndPoint)
data.value = response.data.data
}
return {
getData,data
}
in your component import the function and use it like :
const urlEndPoint=ref('posts')
const {getData:getPosts, data:posts}=useFetch()
getPosts(urlEndPoint.value)

koa js backend is showing error - DB not connected -how to fix this issue

I am also trying different network connections it returns the same error. Please help I am stuck last 15 days in this error. Oh! last one thing my laptop IP is dynamically changing so what can I do know.
this is my mongoose connecter
const mongoose = require('mongoose')
const connection = () =>{
const str = 'mongodb://localhost:27017/524'
mongoose.connect(str , () =>{
console.log("Connection is successfull")
} )
}
module.exports = {connection }
this is server js
const koa = require('koa')
const cors = require('koa-cors')
const bodyParser = require('koa-parser')
const json = require('koa-json')
const {connection} = require('./dal')
const userRouter = require('./Router/userRouter')
const app = new koa()
const PORT = 8000
app.use(cors())
app.use(bodyParser())
app.use(json())
app.use(userRouter.routes()).use(userRouter.allowedMethods())
app.listen(PORT, ()=>{
console.log(`Server is running on port ${PORT}`)
connection();
})
this is modle class
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const UserSchema = new Schema ({
name:{
type:String,
required:true
},
email:{
type:String,
required:true,
unique:true
},
password:{
type:String,
required:true
},
role:{
type: Number,
default: 0
}
},{
timestamps:true
})
const User = mongoose.model('User', UserSchema)
module.exports = User
this is login route
const KoaRouter = require('koa-router')
const { register, login ,getAll } = require('../API/userAPI')
const userRouter = new KoaRouter({prefix: '/user'})
userRouter.post('/register', register)
userRouter.post('/login', login)
userRouter.get ('/get' , getAll)
module.exports = userRouter;
this is my contraller
const UserModel = require('../models/user.model')
const bcrypt = require('bcrypt')
const register = async (ctx) => {
try{
const user = ctx.request.body
const {name, email, password, role} = user
if (!name || !email || !password){
return (ctx.body = { message: "fill" });
}
else{
const exist = await UserModel.findOne({email})
if(exist){
return (ctx.body = { message: "User already exists" });
}else{
const salt = await bcrypt.genSalt();
const hashpassword = await bcrypt.hash(password, salt)
const newUser = new UserModel({
name,
email,
password : hashpassword,
role
})
await newUser.save()
return (ctx.body = { message: "User Registered" });
}
}
}catch(err){
console.log(err.message)
return (ctx.body = { message: err.message });
}
}
const login = async (ctx) => {
try{
const {email, password} = ctx.request.body
const user = await UserModel.findOne({email})
if (!user){
return ( ctx.body = {message:"User does not exist"})
}
else {
const isMatch = await bcrypt.compare(password, user.password)
if (!isMatch) {
return (ctx.body = { message:"Wrong Password"})
}else{
return (ctx.body = { user})
}
}
}catch(err){
return (ctx.body= {err})
}
}
const getAll = async (ctx) => {
try{
const users = await UserModel.find()
return (ctx.body = users)
}catch(err){
return (ctx.body= {err})
}
}
module.exports = {register, login ,getAll}
.
how to fix this.any ideas.Can any body guide me with this scenario.

How to use SSR with Redux in Next.js(Typescript) using next-redux-wrapper? [duplicate]

This question already has an answer here:
next-redux-wrapper TypeError: nextCallback is not a function error in wrapper.getServerSideProps
(1 answer)
Closed 1 year ago.
Using redux with SSR in Next.js(Typescript) using next-redux-wrapper, but getting error on this line
async ({ req, store })
Says, Type 'Promise' provides no match for the signature '(context: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>): Promise<GetServerSidePropsResult<{ [key: string]: any; }>>
Property 'req' does not exist on type 'Store<EmptyObject & { filterReducer: never; }, any> & { dispatch: unknown; }'.
Property 'store' does not exist on type 'Store<EmptyObject & { filterReducer: never; }, any> & { dispatch: unknown; }'
Here is my SSR code:-
export const getServerSideProps: GetServerSideProps = wrapper.getServerSideProps(async ({ req, store }) => {
let { query } = req
let searchCategory = query.category?.toString().toLowerCase().replace(/ /g, "-");
const apolloClient = initializeApollo();
const response = await apolloClient.query({
query: GET_PRODUCT_BY_CATEGORY,
variables: {
numProducts: 10,
category: searchCategory
}
});
await store.dispatch(getProducts(response));
});
You're calling wrapper.getServerSideProps in a wrong way.
Try like the following:
export const getServerSideProps = wrapper.getServerSideProps(
store => async ({req, res, query}) => {
// do your stuff with store and req
}
);
If you're looking for a working demo, you can visit my old answer
This code base could help you. ("next": "10.1.3")
Try using getInitialProps instead of getServerSideProps.
This works in my case. Like code below:
Try
in _app.js
import { wrapper } from '/store';
function MyApp(props) {
const { Component, pageProps } = props;
...
return (
<Component {...pageProps} />
)
}
App.getInitialProps = async props => {
const { Component, ctx } = props;
const pageProps = Component.getInitialProps
? await Component.getInitialProps(ctx)
: {};
//Anything returned here can be accessed by the client
return { pageProps: pageProps, store: ctx.store };
};
export default wrapper.withRedux(App);
store.js file:
const makeStore = props => {
if (!isEmpty(props)) {
return createStore(reducer, bindMiddleware([thunkMiddleware]));
} else {
const { persistStore, persistReducer } = require('redux-persist');
const persistConfig = {
key: 'root',
};
const persistedReducer = persistReducer(persistConfig, reducer); // Create a new reducer with our existing reducer
const store = createStore(
persistedReducer,
bindMiddleware([thunkMiddleware])
); // Creating the store again
store.__persistor = persistStore(store); // This creates a persistor object & push that persisted object to .__persistor, so that we can avail the persistability feature
return store;
}
};
// Export the wrapper & wrap the pages/_app.js with this wrapper only
export const wrapper = createWrapper(makeStore);
in your page:
HomePage.getInitialProps = async ctx => {
const { store, query, res } = ctx;
};

Shared Native instance of worker and main thread

I want to make a progressbar file download. Calculation of an already loaded file needs to be done in a separate thread. That's just not clear how to pass a variable manager
main.js
import * as MyWorker from 'nativescript-worker-loader!~/utils/DownloadManagerProgress.js';
const { DOWNLOAD_SERVICE } = android.content.Context;
const manager = app.android.context.getSystemService(DOWNLOAD_SERVICE);
const worker = new MyWorker();
worker.postMessage({ manager });
worker.onmessage = function (event) {
console.log(event);
};
worker.onerror = function (err) {
console.log(`An unhandled error occurred in worker: ${err.filename}, line:
${err.lineno} :`);
console.log(err.message);
};
DownloadManagerProgress.js
import 'globals';
global.onmessage = (msg) => {
const { manager } = msg.data;
const query = new android.app.DownloadManager.Query();
const cursor = manager.query(query);
};
Error:
'Uncaught TypeError: Cannot read property \'query\' of undefined'
If I create an object in the worker, an error also appears
DownloadManagerProgress.js
import 'globals';
import * as app from 'application';
global.onmessage = (msg) => {
const { DOWNLOAD_SERVICE } = android.content.Context;
const manager = app.android.context.getSystemService(DOWNLOAD_SERVICE);
const query = new android.app.DownloadManager.Query();
const cursor = manager.query(query);
};
error:
Uncaught TypeError: Cannot read property \'getSystemService\' of undefined'
Сould help me. Thanks.

Resources