Why is CoinbaseWalletConnector not working (wagmi)?
I use the wagmi library to create a dap, Wallet connect does not connect during work. All other wallets work correctly, Wallet connect gives an error.
Error:
Uncaught ReferenceError: Buffer is not defined
at Object.__ (QRCode.js:27:1)
enter image description he
App.
In App I import all the necessary modules, creating a client
//App
import { WagmiConfig, createClient } from "wagmi";
import { configureChains } from "wagmi";
import { avalanche, bsc, mainnet } from '#wagmi/core/chains'
import { infuraProvider } from "wagmi/providers/infura";
import { publicProvider } from "wagmi/providers/public";
import { CoinbaseWalletConnector } from "wagmi/connectors/coinbaseWallet";
import { MetaMaskConnector } from "wagmi/connectors/metaMask";
import { WalletConnectConnector } from 'wagmi/connectors/walletConnect'
// API key for Ethereum node
// Two popular services are Infura (infura.io) and Alchemy (alchemy.com)
const infuraId = process.env.INFURA_ID;
const defaultChains = [mainnet, avalanche, bsc]
// Configure chains for connectors to support
const { chains } = configureChains(defaultChains, [
infuraProvider({ infuraId }),
publicProvider(),
]);
// Set up connectors
export const connectors = [
new CoinbaseWalletConnector({
chains,
options: {
appName: "wagmi demo",
qrcode: true,
},
}),
new WalletConnectConnector({
chains,
options: {
infuraId,
qrcode: true,
},
}),
new MetaMaskConnector({
chains,
}),
];
const client = createClient({
autoConnect: false,
connectors,
});
function App() {
return (
<>
<WagmiConfig client={client}>
<Home />
</WagmiConfig>
</>
);
}
My component
In my main component I write onclick() to handle wallets
//My component
import { useConnect } from "wagmi";
const Component = (props) => {
const { connect, connectors } = useConnect();
return (
<>
<WalletButton img={metaMask}
title={"MetaMask"}
onPress={() => { connect({ connector: connectors[2] }) }}
/>
<WalletButton img={coinbase}
title={"Coinbase wallet"}
onPress={() => { connect({ connector: connectors[0] }) }}
/>
<WalletButton img={walletConnectImg}
title={"Wallet connect"}
onPress={() => { connect({ connector: connectors[1] }) }}/>
</>
)
}
Who faced a similar problem? Help XD
Related
I have just created a fresh Next app, and after adding line no. 6, I'm getting error. Why?
import Head from "next/head";
import Image from "next/image";
import styles from "../styles/Home.module.css";
import { useConnectWallet, useSetChain, useWallets } from "#web3-onboard/react";
const Home = () => {
const [{ wallet }, connect, disconnect] = useConnectWallet();
const [{ chains, connectedChain, settingChain }, setChain] = useSetChain();
const connectedWallets = useWallets();
return (
<div className={styles.container}>
<Head>
<title>New - emax</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<p>Instantly deploy your Next.js site to a public URL with Vercel.</p>
</main>
</div>
);
};
You need to import and call the init function from #web3-onboard/react before any hooks (eg. useConnectWallet()) can be used.
import {
init,
useConnectWallet,
useSetChain,
useWallets
} from '#web3-onboard/react'
Check here for exact example - https://socket.dev/npm/package/#web3-onboard/react
first call init look like this sample :
import React from 'react'
import {
init,
useConnectWallet,
useSetChain,
useWallets
} from '#web3-onboard/react'
import injectedModule from '#web3-onboard/injected-wallets'
import trezorModule from '#web3-onboard/trezor'
import ledgerModule from '#web3-onboard/ledger'
import walletConnectModule from '#web3-onboard/walletconnect'
import walletLinkModule from '#web3-onboard/walletlink'
import portisModule from '#web3-onboard/portis'
import fortmaticModule from '#web3-onboard/fortmatic'
import torusModule from '#web3-onboard/torus'
import keepkeyModule from '#web3-onboard/keepkey'
const injected = injectedModule()
const walletLink = walletLinkModule()
const walletConnect = walletConnectModule()
const portis = portisModule({
apiKey: 'b2b7586f-2b1e-4c30-a7fb-c2d1533b153b'
})
const fortmatic = fortmaticModule({
apiKey: 'pk_test_886ADCAB855632AA'
})
const torus = torusModule()
const ledger = ledgerModule()
const keepkey = keepkeyModule()
const trezorOptions = {
email: 'test#test.com',
appUrl: 'https://www.blocknative.com'
}
const trezor = trezorModule(trezorOptions)
const web3Onboard = init({
wallets: [
ledger,
trezor,
walletConnect,
keepkey,
walletLink,
injected,
fortmatic,
portis,
torus
],
chains: [
{
id: '0x1',
token: 'ETH',
label: 'Ethereum Mainnet',
rpcUrl: 'https://mainnet.infura.io/v3/ababf9851fd845d0a167825f97eeb12b'
},
{
id: '0x3',
token: 'tROP',
label: 'Ethereum Ropsten Testnet',
rpcUrl: 'https://ropsten.infura.io/v3/ababf9851fd845d0a167825f97eeb12b'
},
{
id: '0x4',
token: 'rETH',
label: 'Ethereum Rinkeby Testnet',
rpcUrl: 'https://rinkeby.infura.io/v3/ababf9851fd845d0a167825f97eeb12b'
},
{
id: '0x89',
token: 'MATIC',
label: 'Matic Mainnet',
rpcUrl: 'https://matic-mainnet.chainstacklabs.com'
}
],
appMetadata: {
name: 'Blocknative',
icon: '<svg><svg/>',
description: 'Demo app for Onboard V2',
recommendedInjectedWallets: [
{ name: 'MetaMask', url: 'https://metamask.io' },
{ name: 'Coinbase', url: 'https://wallet.coinbase.com/' }
]
}
})
function App() {
const [{ wallet, connecting }, connect, disconnect] = useConnectWallet()
const [{ chains, connectedChain, settingChain }, setChain] = useSetChain()
const connectedWallets = useWallets()
return (
<div>
<button onClick={() => connect()}>
{connecting ? 'connecting' : 'connect'}
</button>
{wallet && (
<div>
<label>Switch Chain</label>
{settingChain ? (
<span>Switching chain...</span>
) : (
<select
onChange={({ target: { value } }) =>
console.log('onChange called') || setChain({ chainId: value })
}
value={connectedChain.id}
>
{chains.map(({ id, label }) => {
return <option value={id}>{label}</option>
})}
</select>
)}
<button onClick={() => disconnect(wallet)}>
Disconnect Wallet
</button>
</div>
)}
{connectedWallets.map(({ label, accounts }) => {
return (
<div>
<div>{label}</div>
<div>Accounts: {JSON.stringify(accounts, null, 2)}</div>
</div>
)
})}
</div>
)
}
export default App
see here
I'm trying to retrieve data from an existing database. I recently switched to bare workflow from Expo managed, trying to test react-native-sqlite-storage with TypeORM. However, TypeORM raw query keeps returning an empty array and I have no idea why.
Here's my code and it is based on this example https://dev.to/jgabriel1/expo-sqlite-typeorm-4mn8
DictionaryScreen.js
function DictionaryScreen(props) {
const { ejRepository } = useDatabaseConnection();
const handleinputWord = async () => {
console.log(props.inputWord); //=>this console.logs the text from the input below
try {
const results = await ejRepository.getWordandMean(props.inputWord);
console.log(results); //=> Here I expect an array of the query result but it only returns []
} catch (error) {
console.log(error)
}
}
return(
<View style={styles.searchContainer}>
<MaterialCommunityIcons name="text-search" color="white" size={30}/>
<TextInput
style={styles.input}
onChangeText={props.updateTextInput}
onSubmitEditing={handleinputWord}
value={props.inputWord}
placeholder='Look up the word (Type exactly)'
keyboardType="default"
/>
<StatusBar style='light' />
</View>
)
}
const mapStateToProps = state => {
return {
inputWord: state.inputWord
}
};
const mapDispatchToProps = {updateTextInput};
export default connect(mapStateToProps, mapDispatchToProps) (DictionaryScreen);
repository.ts
export class EJRepository {
private ormRepository: Repository<EJModel>;
constructor(connection: Connection) {
this.ormRepository = connection.getRepository(EJModel);
}
public async getWordandMean(props: any): Promise<EJModel> {
console.log(props); //=> this returns the same text from DictionaryScreen
const results = await this.ormRepository.query(
`SELECT * FROM ejmodel WHERE word LIKE '%${props}%';`, [props]);
return results;
}
}
connection.tsx
interface DatabaseConnectionContextData {
ejRepository: EJRepository;
}
const DatabaseConnectionContext = createContext<DatabaseConnectionContextData>(
{} as DatabaseConnectionContextData,
);
export const DatabaseConnectionProvider: React.FC = ({ children }) => {
const [connection, setConnection] = useState<Connection | null>(null);
const connect = useCallback(async () => {
const createdConnection = await createConnection({
type: 'react-native',
name: "ejdict.v1.0",
database: '***.db',
entities: [EJModel],
location: 'default',
migrations: [ejdict1621603544180],
migrationsRun: true,
synchronize: false,
logging: true,
extra: {createFromLocation: '/Users/***/***/ios/***/www/***.db' }
});
setConnection(createdConnection);
}, []);
useEffect(() => {
if (!connection) {
connect();
}
}, [connect, connection]);
if (!connection) {
return <ActivityIndicator />;
}
return (
<DatabaseConnectionContext.Provider
value={{
ejRepository: new EJRepository(connection),
}}
>
{children}
</DatabaseConnectionContext.Provider>
);
};
export function useDatabaseConnection() {
const context = useContext(DatabaseConnectionContext);
return context;
}
EJModel.ts
import {Entity, PrimaryColumn, Column} from "typeorm";
#Entity({name: "ejmodel"})
export class EJModel {
#PrimaryColumn({type: 'integer'})
item_id: number;
#Column({type: 'text'})
word: string;
#Column({type: 'text'})
mean: string;
#Column({type: 'integer'})
level: number;
}
PS: Is it an unusual attempt to load an existing database on a React Native project? Working examples are almost no existent. I once made it work on Expo, but I realised I needed migration functionality and tried to do the same thing with TypeORM wasting lots of time...
I have found the solution for this problem by following step
adjust the entity of the table to
#Entity({
name: YOUR_TABLE_NAME,
synchronize: false,
})
Put the existed database into dir
android/app/src/main/assets or android/app/src/main/assets/www
Typeorm declare
export const AppDataSource = new DataSource({
type: "react-native",
database: database.db,
location: "default",
synchronize: true,
entities: [YOUR_ENTITY],
logging: ["error", "query", "schema"],
});
//note that can set to false if you want all tables to not synchronize or can set individually in each Entity like step 1.
4) In your index.android.js or App.js file, openDatabase to get connect to the database.
SQLite.openDatabase(
{
name: "database.db",
createFromLocation: "~database23_02_17.db",
location: "default",
},
() => {
console.log("db connection success");
},
() => {
console.log("db connection error");
}
);
Uninstall the app if you've already installed in your physical device (because the app will not update the database file) and then run build again
cd android &&./gradlew clean
cd .. && react-native run-android
I'm trying to integrate Stripe payment into React Native application and I'm using code for reference that worked on React js project but I can't seem to get it working here. I'm still newbie so any help would be really appreciated.
import { CardElement, useElements, useStripe } from "#stripe/react-stripe-js"
import axios from "axios"
import React, { useState } from 'react'
import { View, Text, Button } from 'react-native'
const CARD_OPTIONS = {
iconStyle: "solid",
style: {
base: {
iconColor: "#c4f0ff",
fontWeight: 500,
fontFamily: "Roboto, Open Sans, Segoe UI, sans-serif",
fontSize: "16px",
fontSmoothing: "antialiased",
":-webkit-autofill": { color: "#fce883" },
"::placeholder": { color: "#87bbfd" }
},
invalid: {
iconColor: "#ffc7ee",
color: "#ffc7ee"
}
}
}
export default function PaymentForm() {
const [success, setSuccess ] = useState(false)
const stripe = useStripe()
const elements = useElements()
const handleSubmit = async () => {
const {error, paymentMethod} = await stripe.createPaymentMethod({
type: "card",
card: elements.getElement(CardElement)
})
if(!error) {
try {
const {id} = paymentMethod
const response = await axios.post("http://localhost:4000/payment", {
amount: 1000,
id
})
if(response.data.success) {
console.log("successful payment")
setSuccess(true)
}
} catch (error) {
console.log("Error", error)
}
}else {
console.log(error.message)
}
}
return (
<>
{!success ?
<View>
<CardElement options={CARD_OPTIONS}/>
<Button
title="Pay"
onPress={handleSubmit} >
</Button>
<Text>Hello1</Text>
</View>
:
<View>
<Text>Purchase successful</Text>
</View>
}
</>
)
}
The Error I'm getting:
View config getter callback for component 'div' must be a function (received 'undefined'). Make sure to start component names with a capital letter.
And from experimenting I noticed that when commenting out
<CardElement />
it got rid of error.
Unfortunately this use of the CardElement is not possible in React Native without something to act as a bridge to the native components.
In a recent issue of the Stripe Dev newsletter, there is a form to share details of your integration and express interest in hearing more about Stripe's work with React Native. I strongly suggest filling that out to explain what you're working on!
I am working on a rich text editor used for converting plain html to editor content with next js for ssr. I got this error window is not defined so I search a solution to this github link
It used a dynamic import feature of next js.
Instead of importing the Editor directly import { Editor } from "react-draft-wysiwyg";
It uses this code to dynamically import the editor
const Editor = dynamic(
() => {
return import("react-draft-wysiwyg").then(mod => mod.Editor);
},
{ ssr: false }
);
But still I'm getting this error though I already installed this react-draft-wysiwyg module
ModuleParseError: Module parse failed: Unexpected token (19:9)
You may need an appropriate loader to handle this file type.
| import dynamic from "next/dynamic";
| var Editor = dynamic(function () {
> return import("react-draft-wysiwyg").then(function (mod) {
| return mod.Editor;
| });
And this is my whole code
import React, { Component } from "react";
import { EditorState } from "draft-js";
// import { Editor } from "react-draft-wysiwyg";
import dynamic from "next/dynamic";
const Editor = dynamic(
() => {
return import("react-draft-wysiwyg").then(mod => mod.Editor);
},
{ ssr: false }
);
class MyEditor extends Component {
constructor(props) {
super(props);
this.state = { editorState: EditorState.createEmpty() };
}
onEditorStateChange = editorState => {
this.setState({ editorState });
};
render() {
const { editorState } = this.state;
return (
<div>
<Editor
editorState={editorState}
wrapperClassName="rich-editor demo-wrapper"
editorClassName="demo-editor"
onEditorStateChange={this.onEditorStateChange}
placeholder="The message goes here..."
/>
</div>
);
}
}
export default MyEditor;
Please help me guys. Thanks.
Here is a workaround
import dynamic from 'next/dynamic'
import { EditorProps } from 'react-draft-wysiwyg'
// install #types/draft-js #types/react-draft-wysiwyg and #types/draft-js #types/react-draft-wysiwyg for types
const Editor = dynamic<EditorProps>(
() => import('react-draft-wysiwyg').then((mod) => mod.Editor),
{ ssr: false }
)
The dynamic one worked for me
import dynamic from 'next/dynamic';
const Editor = dynamic(
() => import('react-draft-wysiwyg').then((mod) => mod.Editor),
{ ssr: false }
)
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
const TextEditor = () => {
return (
<>
<div className="container my-5">
<Editor
toolbarClassName="toolbarClassName"
wrapperClassName="wrapperClassName"
editorClassName="editorClassName"
/>
</div>
</>
)
}
export default TextEditor
Draft.js WYSWYG with Next.js and Strapi Backend, Create and View Article with Image Upload
import React, { Component } from 'react'
import { EditorState, convertToRaw } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import dynamic from 'next/dynamic';
const Editor = dynamic(
() => import('react-draft-wysiwyg').then(mod => mod.Editor),
{ ssr: false })
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
export default class ArticleEditor extends Component {
constructor(props) {
super(props);
this.state = {
editorState: EditorState.createEmpty()
};
}
onEditorStateChange = (editorState) => {
this.setState({
editorState,
});
this.props.handleContent(
convertToRaw(editorState.getCurrentContent()
));
};
uploadImageCallBack = async (file) => {
const imgData = await apiClient.uploadInlineImageForArticle(file);
return Promise.resolve({ data: {
link: `${process.env.NEXT_PUBLIC_API_URL}${imgData[0].formats.small.url}`
}});
}
render() {
const { editorState } = this.state;
return (
<>
<Editor
editorState={editorState}
toolbarClassName="toolbar-class"
wrapperClassName="wrapper-class"
editorClassName="editor-class"
onEditorStateChange={this.onEditorStateChange}
toolbar={{
options: ['inline', 'blockType', 'fontSize', 'fontFamily', 'list', 'textAlign', 'colorPicker', 'link', 'embedded', 'emoji', 'image', 'history'],
inline: { inDropdown: true },
list: { inDropdown: true },
textAlign: { inDropdown: true },
link: { inDropdown: true },
history: { inDropdown: true },
image: {
urlEnabled: true,
uploadEnabled: true,
uploadCallback: this.uploadImageCallBack,
previewImage: true,
alt: { present: false, mandatory: false }
},
}}
/>
<textarea
disabled
value={draftToHtml(convertToRaw(editorState.getCurrentContent()))}
/>
</>
)
}
}
Try to return the Editor after React updates the DOM using useEffect hook. For instance:
const [editor, setEditor] = useState<boolean>(false)
useEffect(() => {
setEditor(true)
})
return (
<>
{editor ? (
<Editor
editorState={editorState}
wrapperClassName="rich-editor demo-wrapper"
editorClassName="demo-editor"
onEditorStateChange={this.onEditorStateChange}
placeholder="The message goes here..."
/>
) : null}
</>
)
I use Gatsby with Typescript to create a blog based on Contentful CMS.
I have FeaturedPost component which I want to put in the main page and this is the code:
FeaturedPost.tsx
interface IProps {
data: {
contentfulPost: ContentfulPost;
};
}
const FeaturedPost: React.FunctionComponent<IProps> = ({ data }) => {
const { title, description } = data.contentfulPost;
return (
<>
<Header>{title}</Header>;
<div>{description}</div>
</>
);
};
export const query = graphql`
query featuredPost($slug: String) {
contentfulPost(slug: { eq: $slug }) {
title
slug
description {
childMarkdownRemark {
html
}
}
}
}
`;
export default FeaturedPost;
This is my index page code:
index.tsx
const IndexPage: React.FunctionComponent<P> = () => {
return (
<Layout>
<SEO
title="Home"
keywords={[`gatsby`, `application`, `react`]}
description="Index for something I can't remember?!"
/>
<FeaturedPost />
<h1>Hi people</h1>
<p>Welcome to your new Gatsby site.</p>
<p>Now go build something great.</p>
<div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }} />
</Layout>
);
};
export default IndexPage;
Tslint now expects that I pass a prop called data to FeaturedPost component since I implement interface IProps on FeaturedPost, but actually there is no data to get passed.
FeaturedPost itself receives it as a response from the sent query. Do you have any idea what's wrong with this code or how can I satisfy the linter?
In Gatsby v2, graphql queries in non-page components will be ignored. Use StaticQuery instead. Here's a small example:
import * as React from 'react'
import { StaticQuery, graphql, Link } from 'gatsby'
type TOCDataType = {
readonly allSitePage: {
edges: [
{
node: {
id: string
path: string
}
}
]
}
}
const TableOfContents: React.FunctionComponent<{}> = () => (
<StaticQuery
query={graphql`
query SitePageQuery {
allSitePage {
edges {
node {
id
path
}
}
}
}
`}
render={(data: TOCDataType) => (
<div>
{data.allSitePage.edges.map(({ node }) => (
<li key={node.id}>
<Link to={node.path}>{node.path}</Link>
</li>
))}
</div>
)}
/>
)
export default TableOfContents