Nextjs 13.0.2 and Ethers why is my Provider undefined? - next.js

I'm trying to access the ethers provider like this in Nextjs 13.0.1:
import { ethers } from "ethers";
export const signMessage = () => {
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
try {
signer.signMessage("Hey hey").then((result) => {
console.log(result);
});
} catch (error) {
// handle error
console.log(error);
}
};
But it always gives me the error:
Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'Web3Provider')
I've tried different providers but always get the error message above.
Someone knows why it's working for Nextjs 12 but not for Next 13?

I think you are using version 6 in next13. if you install
"ethers": "^5.6.4",
in next-13, it will work.
I think you previously had next-12 project with version 5, and now installing new version on next-13
in ethers v6 all of those
export {
getDefaultProvider,
Block, FeeData, Log, TransactionReceipt, TransactionResponse,
AbstractSigner, NonceManager, VoidSigner,
AbstractProvider,
FallbackProvider,
JsonRpcApiProvider, JsonRpcProvider, JsonRpcSigner,
BrowserProvider,
AlchemyProvider, AnkrProvider, CloudflareProvider, EtherscanProvider,
InfuraProvider, PocketProvider, QuickNodeProvider,
IpcSocketProvider, SocketProvider, WebSocketProvider,
EnsResolver,
Network
} from "./providers/index.js";
are imported like this
import { BrowserProvider } from "ethers";
const providerr = new BrowserProvider(window.ethereum);
this is how I set a component to connect
const Test = () => {
const [provider, setProvider] = useState();
useEffect(() => {
const browserProvider = new BrowserProvider(window.ethereum);
setProvider(browserProvider);
}, []);
const connect = async () => {
await provider.send("eth_requestAccounts");
};
return (
<div>
<button onClick={connect}>connect</button>
</div>
);
};
export default Test;

If you are using "ethers": "^6.0.2" like me then use this :
const web3Provider = new ethers.BrowserProvider(window.ethereum);
Also then getting signer you should remember that web3Provider.getSigner() will return a promise so use await or then
const signer = await web3Provider.getSigner();
Check more on ethers documentation

Related

PromiseĀ {<pending>} Graphql, and strapi with nextjs

With GraphQL and nextjs, I'm trying to retrieve some data from strapi.
When I try to access these data from the other file and display them on the UI, I get this error PromiseĀ {} in console.log.
This is what i tried
sliderAdapter.js
import { fetchSlider } from "./apiClient";
export const sliderAdapter = async (data, locale, url) => {
const sl = await fetchSlider();
const deepDownSlides = sl.data?.slides?.data;
if (deepDownSlides.length > 0) {
const slider = deepDownSlides[0]?.attributes?.slider;
// console.log("slider", slider);
return slider;
}
// This code is working but not properly, just return the data into the console.
return "";
};
fetchSlider is the file where i put the query.
Next:
import { sliderAdapter } from "../../lib/sliderAdapter";
const Slider = (data) => {
const slide= sliderAdapter(data)
console.log("slide", slide)
If anyone knows or can find the issues, plz let me know :)
Your function is asynchronous so you have to retrieve the value once the promise is resolved
sliderAdapter(data).then(slide=>console.log(slide))

Fetching firebase storage file URL in Next.js app returns XMLHttpRequest ReferenceError

I have setup Next.js (11) app with working connection to the firebase version 8.7.
I got an issue on getting donwload URL for image:
If I'd create a function (example below) to fetch the uploaded image - assume it is there & I know its name and location. It will work only once (dev env)
After any route change or page refresh (not on code change assuming I do not change the route or refresh the page), the app crashes with terminal error:
ReferenceError: XMLHttpRequest is not defined
I get this error when I call both in getStaticProps or in the component itself on the client side
function example:
import firebase from "firebase/app";
import "firebase/storage";
export const getImgUrl = async () => {
const storage = firebase.storage();
const pathReference = storage.ref("user_uploads/my_image.jpg");
pathReference
.getDownloadURL()
.then((url) => {
console.log("my url", url);
})
.catch((error) => {
console.error("error", error);
});
};
I have a bypass solution:
Upgrade to the firebase sdk version 9 (modular one).
Create db & storage:
const initFirebase = () => {
const db = getFirestore(firebaseApp)
const storage = getStorage(firebaseApp)
console.log('Firebase was successfully initialized')
return [db, storage]
}
// Init firebase:
export const [db, storage] = initFirebase()
use it:
const getData = async () => {
console.log('getData runs')
try {
const url = await getDownloadURL(ref(storage, 'landing/land.jpg'))
console.log('getData url:', url)
return url
} catch (error) {
// Handle any errors
}
}
and call getData in getServerSideProps or getStaticProps in any component

TypeError: undefined is not an object (evaluating '_this.getFcmToken')

How to get fcm token from firebase in react-native . Currently I am using these packages
#react-native-firebase/app
#react-native-firebase/messaging
my code
const RegisterScreen = (props) => {
const [fcmToken, setfcmToken] = useState();
useEffect(() => {
messaging()
.getToken()
.then(token => {
return saveTokenToDatabase(token);
});
}, []);
async function saveTokenToDatabase(token) {
console.log(token)
}
}
I want to get fcm token from firebase when any user register in react native but it gives me that error
TypeError: undefined is not an object (evaluating '_this.getFcmToken')
I would recommend to rewrite the code like this:
const RegisterScreen = async (props) => {
const [fcmToken, setfcmToken] = useState();
useEffect(() => {
messaging()
.getToken()
.then((token) => {
return setfcmToken(token);
});
}, []);
async function saveTokenToDatabase(token) {
console.log(token);
}
useEffect(() => {
if (fcmToken) {
saveTokenToDatabase(fcmToken);
}
}, [fcmToken]);
};
From your error message it looks like you try to get the token from this. You either habe an issue with async/await where you try to get it before you set it or an issue with useEffect where you also coult try to get it before it is set to the state. I'm also not sure where to you want to use this in a react function. They don't have this.

Method "Astronomy/execute" not found in meteor

Okay, I build Game DB schema using astronomy package in meteor.
Then I try to add method to it by extending it in server. (server/gamehandle.js)
import {Game} from '../imports/db/game'
import {DDP} from 'meteor/ddp-client'
Game.extend({
meteorMethods: {
AddNewGame(judul){
const invocation = DDP._CurrentInvocation.get()
this.namaGame = judul
this.creator = invocation.userId
this.createdAt = new Date()
return this.save()
}
}
})
But when I try to run the method in app client using callMethod it throw an error that astronomy/execute not found 404.
This the component using it
import {Game} from '../../../db/game'
export function NewGameList(props){
const { isOpen, onOpen, onClose } = useDisclosure()
const [judul, setJudul] = useState('')
const [hasil, setHasil] = useState(null)
const judulChange = (e) => setJudul(e.target.value)
const AddGame = new Game()
const handleSubmit = (e) => {
e.preventDefault()
AddGame.callMethod('AddNewGame', judul, (err, result) => {
result ? setHasil(result) : setHasil(err.message)
console.log(err)
})
}
...
So enlight me, what thing I do wrong?
Finally found the solution from meteor slack.
Just need to imports my db file to main js file in server.

Firebase Deploy Error: Failed to configure trigger

I have following sample function from this tutorial: Asynchronous Programming (I Promise!) with Cloud Functions for Firebase - Firecasts
exports.emailEmployeeReport = functions.database
.ref('/employees/${eid}/reports/${rid}')
.onWrite(event => {
const eid = event.params.eid;
const report = event.data.val().report;
const root = event.data.ref.root;
const mgr_promise = root.child(`/employees/${eid}/manager`).once('value');
const then_promise = mgr_promise.then(snap => {
const mgr_id = snap.val();
const email_promise = root.child(`/employees/${mgr_id}/email`).once('value');
return email_promise;
}).catch(reason => {
// Handle the error
console.log(reason);
});;
const then_promise2 = then_promise.then(snap => {
const email = snap.val();
const emailReportPromise = sendReportEmail(email, report);
return emailReportPromise;
}).catch(reason => {
// Handle the error
console.log(reason);
});
return then_promise2;
});
var sendReportEmail = function (email, report) {
const myFirstPromise = new Promise((resolve, reject) => {
// do something asynchronous which eventually calls either:
//
setTimeout(function () {
try {
var someValue = "sendReportEmail";
console.log(someValue);
// fulfilled
resolve(someValue);
}
catch (ex) {
// rejected
reject(ex);
}
}, 2000);
});
return myFirstPromise;
}
once I run firebase deploy command, eventually I am getting following error:
functions[emailEmployeeReport]: Deploy Error: Failed to configure
trigger
providers/google.firebase.database/eventTypes/ref.write#firebaseio.com
(emailEmployeeReport)
I also have a simple hello-world method and a similar trigger method, and they deploy fine.
Am I missing something here?
The syntax for wildcards in the database reference does not have "$".
Try the following:
exports.emailEmployeeReport = functions.database
.ref('/employees/{eid}/reports/{rid}')

Resources