I am unable to detect window.ethereum in Metamask mobile but works fine in metamask extension and Trust Wallet. I am using react with vite.
Also I am writing code in repl.it ide with react template.
Here is the full code.
import React from 'react';
import { ethers } from "ethers";
function dosomething(){
if(window.ethereum){
const provider = new providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
}
else{
alert('Please install MetaMask first.');
}
}
function NewFun() {
if (window.ethereum) {
dosomething();
}
else {
window.addEventListener('ethereum#initialized', dosomething, {
once: true,
});
// If the event is not dispatched by the end of the timeout,
// the user probably doesn't have MetaMask installed.
setTimeout(dosomething, 5000); // 5 seconds
}
}
function Test() {
return(
<main>
<button onClick={NewFun}>Hiii</button>
Hii
</main>);
}
export default Test;
Basic Html , js works fine.
Related
I created a Google Cloud Platform account, and made a simple hello_world type Python "Cloud Function" that just spits out some simple text. I made this function "HTTP" accessible and only able to be called/authenticated by a "Service Account" that I made for the purpose of calling this very function. I generated a key for this "Service Account" and downloaded the json file for the key.
The problem is that I can't find any documentation on how to call this function with my service account in a next.js app. I tried this:
import React from 'react';
import { Button } from 'react-bootstrap';
import { GoogleAuth } from 'google-auth-library';
const projectId = 'gtwitone';
const keyFilename = '/Users/<myusername>/path/to/cloudfunction/credentials.json';
class Middle extends React.Component {
handleClick() {
console.log('this is:', this);
}
// This syntax ensures `this` is bound within handleClick. // Warning: this is *experimental* syntax. handleClick = () => { console.log('this is:', this); }
/* async listFunctions() {
const [functions] = await client.listFunctions();
console.info(functions);
} */
async runGoogleCloudFunctionTest() {
// Define your URL, here with Cloud Run but the security is exactly the same with Cloud Functions (same underlying infrastructure)
const url = "https://us-central1-<projectname>.cloudfunctions.net/<functionname>"
//Example with the key file, not recommended on GCP environment.
const auth = new GoogleAuth({keyFilename: keyFilename})
//Create your client with an Identity token.
const client = await auth.getIdTokenClient(url);
const res = await client.request({url});
console.log(res.data);
}
render() {
return (
<div className="col-md-12 text-center">
<Button variant='primary' onClick={this.runGoogleCloudFunctionTest}>
Click me
</Button>
</div>
);
}
}
export default Middle;
But I got this error in my terminal:
<myusername>#<mycomputername> <thisnextjsappdirectory> % yarn dev
yarn run v1.22.17
$ next dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
wait - compiling...
event - compiled client and server successfully in 267 ms (124 modules)
wait - compiling / (client and server)...
wait - compiling...
error - ./node_modules/google-auth-library/build/src/auth/googleauth.js:17:0
Module not found: Can't resolve 'child_process'
Import trace for requested module:
./node_modules/google-auth-library/build/src/index.js
./components/Middle.tsx
./pages/index.tsx
https://nextjs.org/docs/messages/module-not-found
Native Node.js APIs are not supported in the Edge Runtime. Found `child_process` imported.
Could not find files for / in .next/build-manifest.json
Could not find files for / in .next/build-manifest.json
^C
<myusername>#<mycomputername> <thisnextjsappdirectory> %
I know that this is problem with server side rendering in my Next.js app and people recommend using a client side package like this https://github.com/google/google-api-javascript-client. But google-api-javascript-client doesn't have any documentation on authenticating with a .json credentials file instead of an API KEY which I do not have.
In short how do I get my app to work and run the Google Cloud function with a .json credentials file for am authenticated service account?
I fixed it by simply moving the GoogleAuth api call to the pages/api route.
pages/api/google.ts
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next"
import { GoogleAuth } from "google-auth-library"
export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
const url = process.env.FUNCTION_URL as string
//Example with the key file, not recommended on GCP environment.
const auth = new GoogleAuth({ keyFilename: process.env.KEYSTORE_PATH })
//Create your client with an Identity token.
const client = await auth.getIdTokenClient(url)
const result = await client.request({ url })
console.log(result.data)
res.json({ data: result.data })
}
components/Middle.tsx
import React from "react"
import { Button } from "react-bootstrap"
class Middle extends React.Component {
handleClick() {
console.log("this is:", this)
}
// this talks with /pages/api/google
async imCallingAnAPI() {
const result = await fetch("/api/google")
console.log({ result })
}
render() {
return (
<div className="col-md-12 text-center">
<Button variant="primary" onClick={this.imCallingAnAPI}>
Click me
</Button>
</div>
)
}
}
export default Middle
pages/index.tsx
import type { NextPage } from 'next'
import Header from '../components/Header';
import Footer from '../components/Footer';
import Middle from '../components/Middle';
const Home: NextPage = () => {
return (
<><main className='d-flex flex-column min-vh-100'>
<Header />
<br></br>
<br></br>
<Middle />
</main>
<footer>
<Footer />
</footer>
</>
)
}
export default Home
I think that next.js has trouble loading GoogleAuth in a component. I'm not 100% sure why, but I think it has to do with next.js not knowing exactly how to handle GoogleAuth with server-side rendering.
axios code:
import Axios from "axios";
export const getBlogPosts = async (setter) => {
try {
const res = await Axios.get(`https://jsonplaceholder.typicode.com/posts/1`);
if (res.status === 200 && res?.data) {
setter(res?.data);
}
} catch (error) {
console.log(error.message);
}
};
this is my app code :
import React, { useEffect, useState } from "react";
import { getBlogPosts } from "./_helper";
export function TestCustomerCreate() {
const [gridData, setGridData] = useState();
useEffect(() => {
getBlogPosts(setGridData);
}, []);
console.log(gridData);
return (
<div>
<h1>This is test create form</h1>
</div>
);
}
error msg: Request failed with status code 404
but when i'm using fetch its working fine (i'm using "axios": "0.19.2" with Metronic theme react (7.0.8)
Reason for this is in Metronic use axios-mock-adapter for demo purpose, it intercepts axios requests and redirects to mocked handlers. Mock Back-end
To use real REST APIs need to do 2 things.
remove mock initialization. For that remove mock initialization in
the src/index.js or src/main.js file.
Remove API initialization from the src/index or src/main.js
// Remove this to disable mock API
MockService.init();
// API service init
ApiService.init();
I am trying to integrate Google sign in on my react js application. Well the i am using react-google-login package to implement it. Its working perfectly fine when i am launching it via npm start. But the when i am launching my application via a debugger in VSCode and trying to do google sign in it is throwing following error.
And my launch config is
I have already tried, allowing unsecured application to sign in on google settings for my id.
EDIT: Adding Sign in code
import React from "react";
import { GoogleLogin } from "react-google-login";
import {} from "dotenv/config";
const LoginGoogle = () => {
const onSuccess = (res) => {
console.log("Login Sucess currentUSer " + JSON.stringify(res));
};
const onFailure = () => {
console.log("Login Fail");
};
const value = process.env.REACT_APP_GOOGLE_O_AUTH_CLIENT_ID;
return (
<div className="pb-5">
<GoogleLogin
// clientId={process.env.REACT_APP_GOOGLE_O_AUTH_CLIENT_ID}
clientId={value}
buttonText="Login this shit"
onSuccess={onSuccess}
onFailure={onFailure}
cookiePolicy={"single_host_origin"}
className="mt-5"
isSignedIn={true}
></GoogleLogin>
</div>
);
};
export default LoginGoogle;
I want to add service worker in my react project.
Project is ready the default Service seems not to works.
Even When I try to import this, it gives this error:
Attempted import error: './registerServiceWorker' does not contain a default export (imported as 'registerServiceWorker').
Furthermore, how to add files to be cached in the default version serviceWorker file.
If I add my own custom serviceWorker file just like for no-react (framework) application, will it works for react case?
Currently I have these code in my index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { BrowserRouter } from 'react-router-dom'
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root'));
registerServiceWorker();
And in this says : " Attempted import error: './registerServiceWorker' does not contain a default export (imported as 'registerServiceWorker'). "
Service Worker which I am using is as under: (React's Default Code)
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more,
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See /CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
From your error information,there are something wrong with registerServiceWorker.js file.
import registerServiceWorker from './registerServiceWorker';
However,in registerServiceWorker.js file don't have the following
export registerServiceWorker
So, I recommend to add the below to registerServiceWorker.js
export default registerServiceWorker
Edit:
Use this to import js files
import * as registerServiceWorker from './registerServiceWorker';
And use it like this:
registerServiceWorker.unregister();
Edit2:
I think you have some misunderstanding about import/export.So I will explain it here.
If we want to import some file(e.g child.js) into another file(e.g parent.js).In the file like child.js,it must have export.
There are some ways to do so.
1. In Child.js
const child = () => {
}
export default Child
We will be able to import it in parent.js like below.With the default expression, we actually can use any name in the place of Child in the below.(Usually keep them the same.)
import Child from './child.js'
import ChildReplace from './child.js' //This also works, the ChildReplace are actually the Child in the child.js
You may see another way to import.Like this:
import * as registerServiceWorker from './registerServiceWorker';
The * means all the content in registerServiceWorker.js."as registerServiceWorker" are giving all the content a name for us to import them easily.
The way to import file because in the registerServiceWorker.js,there are many export expressions but without export default.
you can import all the functions exported from registerServiceWorker.js file by using
import * as registerServiceWorker from './registerServiceWorker';
and after that you can call any method from that file to your index.js file like -
registerServiceWorker.unregister();
Try this.
create-react-app FolderName
Is just auomatically creates a registerServiceWorker for your app
I am new to ReactJS.
Seem to be having trouble integrating web3 from Metamask in React.
Metamask version: web3#1.0.0-beta.34
import Web3 from 'web3'
let web3;
window.addEventListener('load', function () {
if (typeof window.web3 !== 'undefined') {
web3 = new Web3(window.web3.currentProvider);
} else {
// No web 3 provider
console.log("Please install Metamask");
}
});
export default web3;
Getting the following error:
window is not defined
ReferenceError: window is not defined
at Object../lib/getWeb3.js (lib/getWeb3.js:5:0)
window is not defined on Server, only in client's browser, hence you can't use MetaMask server-side. However, you can connect to INFURA when you want to use web3 in your React component server-side or without MetaMask support.
The simplest way is to use react-web3-provider component.
Add the Web3Provider to your root React component:
import Web3Provider from 'react-web3-provider';
ReactDOM.render(
<Web3Provider
defaultWeb3Provider="https://mainnet.infura.io/YOUR_API_KEY"
loading="Loading..."
>
<App />
</Web3Provider>
)
Then in component where you want to use Web3:
import { withWeb3 } from 'react-web3-provider';
class MyComponent {
render() {
const { web3 } = this.props;
web3.eth.getAccounts(console.log);
// Version 1.0.0-beta.35
return "Web3 version: {web3.version}";
}
}
export default withWeb3(MyComponent);