I can't get the value from the signer.getAddress() function on Ethers.js.
When I try to use "alert" or "console.log" it is fine but I want to display it directly on the page. It says; "object Promise".
Here is my code:
import "./App.css";
import { ethers } from "ethers";
function App() {
const provider = new ethers.providers.Web3Provider(window.ethereum, "any");
const signer = provider.getSigner();
async function connectMetamask() {
await provider.send("eth_requestAccounts", []);
}
async function myAddress() {
await signer.getAddress();
}
return (
<div className="general">
<div className="web3-loader">
<button className="button1" onClick={connectMetamask}>
Connect Metamask
</button>
</div>
<br></br>
<div className="input-area">
<label>{"Your address is: " + myAddress()} </label>
<br></br>
<label>Recipient address:</label>
<input
type="text"
placeholder="Receiver address"
className="input2"
></input>
<br></br>
<label>Amount:</label>
<input
type="text"
placeholder="Amount of ETH"
className="input3"
></input>
</div>
</div>
);
}
export default App;
import "./App.css";
import { ethers } from "ethers";
import {useState} from "react"
function App() {
const [add, setAdd] = useState("")
const provider = new ethers.providers.Web3Provider(window.ethereum, "any");
const signer = provider.getSigner();
async function connectMetamask() {
const res = await provider.send("eth_requestAccounts", []);
setAdd(res);
}
async function myAddress() {
await signer.getAddress();
}
return (
<div className="general">
<div className="web3-loader">
<button className="button1" onClick={connectMetamask}>
Connect Metamask
</button>
</div>
<br></br>
<div className="input-area">
<label>{`your address is ${add}`} </label>
<br></br>
<label>Recipient address:</label>
<input
type="text"
placeholder="Receiver address"
className="input2"
></input>
<br></br>
<label>Amount:</label>
<input
type="text"
placeholder="Amount of ETH"
className="input3"
></input>
</div>
</div>
);
}
export default App;
Related
I built a site in reactjs for a project to be submitted and I'm trying to get the message that I can see (I added in the picture) to be printed to the user.
watch here
fixed but now it says firebase at the start of each message, is there a way to delete it? "Firebase: Password should be at least 6 characters (auth/weak-password)."
this is the code of the page:
import React, { useState } from 'react';
import Add from "../img/AvatarAdd.png"
import { createUserWithEmailAndPassword, updateProfile } from "firebase/auth";
import { auth, db, storage} from "../firebase";
import { ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
import { doc, setDoc } from "firebase/firestore";
import { useNavigate, Link } from 'react-router-dom';
import { errorMessage } from 'stream-chat-react/dist/components/AutoCompleteTextarea/utils';
const Register = () => {
const [err, setErr] = useState(false);
const navigate = useNavigate()
const handleSubmit = async (e)=>{
e.preventDefault();
const displayName = e.target[0].value;
const email = e.target[1].value;
const password = e.target[2].value;
const file = e.target[3].files[0];
try{
const res = await createUserWithEmailAndPassword(auth, email, password);
const storageRef = ref(storage, displayName);
const uploadTask = uploadBytesResumable(storageRef, file);
// Register three observers
uploadTask.on(
(error) => {
setErr(true);
},
() => {
getDownloadURL(uploadTask.snapshot.ref).then( async(downloadURL) => {
await updateProfile(res.user, {
displayName,
photoURL: downloadURL,
});
await setDoc(doc(db, "users", res.user.uid), {
uid: res.user.uid,
displayName,
email,
photoURL: downloadURL,
});
await setDoc(doc(db, "userChats", res.user.uid), {})
navigate("/");
});
}
);
} catch (err) {
setErr(err);
}
};
return (
<div className='formContainer'>
<div className='formWrapper'>
<span className="logo">Trust Yoav</span>
<span className="title">Register</span>
<form onSubmit={handleSubmit}> {/* my form to add user, need to add confirm password */}
<input type="text" placeholder="display name"/>
<input type="email" placeholder="email"/>
<input type="password" placeholder="password"/>
<input style={{display:"none"}} type="file" id="file"/>
<label htmlFor="file" >
<span>Add an avater:</span>
<img style={{ width: 32, cursor: 'pointer'}} src={Add} alt="" />
</label>
<button>Sign Up</button>
{err && <span>{err.message}</span>}
</form>
<p>You do have an account? <Link to="/login">Login</Link></p>
</div>
</div>
);
};
export default Register;
I have tried to search the internet for information about it or try to access it in different forms but I have not been able to.
The catch must catch the error returned by the "createUserWithEmailAndPassword" function.
Where you have
} catch (err) {
setErr(true);
}
replace with
} catch (err) {
setErr(err);
}
And render the error message with
<div className='formContainer'>
<div className='formWrapper'>
<span className="logo">Trust Yoav</span>
<span className="title">Register</span>
<form onSubmit={handleSubmit}> {/* my form to add user, need to add confirm password */}
<input type="text" placeholder="display name"/>
<input type="email" placeholder="email"/>
<input type="password" placeholder="password"/>
<input style={{display:"none"}} type="file" id="file"/>
<label htmlFor="file" >
<span>Add an avater:</span>
<img style={{ width: 32, cursor: 'pointer'}} src={Add} alt="" />
</label>
<button>Sign Up</button>
{err && <span>{err.message}</span>}
</form>
<p>You do have an account? <Link to="/login">Login</Link></p>
</div>
</div>
When I add the location.assign('AllBlog') it doesn't post the data but if I remove it, it works.
import React, { useState } from 'react'
import './PostBlog.css'
import axios from 'axios'
function PostBlog() {
const [title , setTitle] =useState(null);
const [body , setBody] =useState(null);
const [PostDone , setPostDone] =useState(false);
const handelPost =()=>{
axios.post('http://127.0.0.1:7000/postBlog',{
title:title,
body:body
})
setPostDone(()=>true)
}
{PostDone ? window.location.assign('/AllBlog'): null}
return (
<section className='Post-blog'>
<h1 className='post-header-text'> Post what you Like</h1>
<div className='form-post'>
<label>
<h3>title</h3>
<input type="text" className='title-from' onChange={(e)=> {setTitle(e.target.value)}}/>
</label>
<label>
<h3>Pergraph</h3>
<textarea type="text" className='p-from' rows="6" onChange={(e)=>{setBody(e.target.value)}}></textarea>
</label>
{/* <label>
<h3>Upload Image</h3>
<input type="file"/>
</label> */}
<button className='btn una' onClick={()=>handelPost()}>Post</button>
</div>
</section>
)
}
export default PostBlog
Function axios.post is asynchronous. So window.location.assign might be executed before a finish of the request. To fix that make function handelPost asynchronous and add await to axios.post.
const handelPost = async () => {
await axios.post('http://127.0.0.1:7000/postBlog', {
title:title,
body:body
});
setPostDone(() => true);
}
import { initializeApp } from "firebase/app"; import { getStorage } from "firebase/storage";
const firebaseConfig = { ... // here is my API };
const app = initializeApp(firebaseConfig);
const storage = getStorage(app);
export { storage, app };
app.js file
import { useState } from "react";
import "./newProduct.css";
import { storage } from "../../firebase";
import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
export default function NewProduct() {
const [movie, setMovie] = useState(null);
const [img, setImg] = useState(null);
const [imgTitle, setImgTitle] = useState(null);
const [imgSm, setImgSm] = useState(null);
const [trailer, setTrailer] = useState(null);
const [video, setVideo] = useState(null);
const [uploaded, setUploaded] = useState(0);
const handleChange = (e) => {
const value = e.target.value;
setMovie({ ...movie, [e.target.name]: value });
};
const upload = (items) => {
items.forEach((item) => {
const fileName = new Date().getTime() + item.label + item.file.name;
const storageRef = ref(storage, `/items/${fileName}`)
const uploadTask = uploadBytesResumable(storageRef, item);
uploadTask.on(
"state_changed",
(snapshot) => {
const progress =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log("Upload is" + progress + " % done.");
},
(err) => {
console.log(err);
},
() => {
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
setMovie((prevState) => {
return { ...prevState, [item.label]: downloadURL };
});
setUploaded((prev) => prev + 1);
});
}
);
});
};
const handleUpload = (e) => {
e.preventDefault();
upload([
{ file: img, lable: "img" },
{ file: imgTitle, lable: "imgTitle" },
{ file: imgSm, lable: "imgSm" },
{ file: trailer, lable: "trailer" },
{ file: video, lable: "video" },
]);
};
console.log(movie);
return (
<div className="newProduct">
<h1 className="addProductTitle">New Movie</h1>
<form className="addProductForm">
<div className="addProductItem">
<label>Image</label>
<input
type="file"
id="img"
name="img"
onChange={(e) => setImg(e.target.files[0])}
/>
</div>
<div className="addProductItem">
<label>Title image</label>
<input
type="file"
id="imgTitle"
name="imgTitle"
onChange={(e) => setImgTitle(e.target.files[0])}
/>
</div>
<div className="addProductItem">
<label>Thumbnail image</label>
<input
type="file"
id="imgSm"
name="imgSm"
onChange={(e) => setImgSm(e.target.files[0])}
/>
</div>
<div className="addProductItem">
<label>Title</label>
<input
type="text"
placeholder="John Wick"
name="title"
onChange={handleChange}
/>
</div>
<div className="addProductItem">
<label>Description</label>
<input
type="text"
placeholder="description"
name="desc"
onChange={handleChange}
/>
</div>
<div className="addProductItem">
<label>Year</label>
<input
type="text"
placeholder="year"
name="year"
onChange={handleChange}
/>
</div>
<div className="addProductItem">
<label>Genre</label>
<input
type="text"
placeholder="genre"
name="genre"
onChange={handleChange}
/>
</div>
<div className="addProductItem">
<label>Duration</label>
<input
type="text"
placeholder="duration"
name="duration"
onChange={handleChange}
/>
</div>
<div className="addProductItem">
<label>Limit</label>
<input
type="text"
placeholder="limit"
name="limit"
onChange={handleChange}
/>
</div>
<div className="addProductItem">
<label>Is Series?</label>
<select name="isSeries" id="isSeries" onChange={handleChange}>
<option value="false">No</option>
<option value="true">Yes</option>
</select>
</div>
<div className="addProductItem">
<label>Trailer</label>
<input
type="file"
name="trailer"
onChange={(e) => setTrailer(e.target.files[0])}
/>
</div>
<div className="addProductItem">
<label>Video</label>
<input
type="file"
name="video"
onChange={(e) => setVideo(e.target.files[0])}
/>
</div>
{uploaded === 5 ? (
<button className="addProductButton">Create</button>
) : (
<button className="addProductButton" onClick={handleUpload}>
Upload
</button>
)}
</form>
</div>
);
}`
I'm not sure where went wrong, I'm assuming it's one of my useState functions but I'm not sure.
this is what it shows on my console
(I uploaded 5 different files (img, imgTitle, imgSm, trailer, video), but it only retrives one link from the firebase and it sets the name of that property to "undefined" when it's suppose to return 5 different property names.
this is what it's suppose to be like based on the tutorial I followed:
this is my when i add a question on a same document link
this is add_question.jsx
import "./newQuestion.scss"
import Sidebar from '../../components/sidebar/Sidebar'
import Navbar from '../../components/navbar/Navbar'
import { useState } from 'react'
import { db } from '../../firebase'
import { setDoc,addDoc, collection , doc} from '#firebase/firestore'
import { useParams , useNavigate} from 'react-router-dom';
const NewQuestion = () => {
const [question, setQuestion]=useState("");
const [correctanswer, setCorrectAnswer]=useState("");
const [optionone,setOptionOne]=useState("")
const [optiontwo,setOptionTwo]=useState("");
const [optionthree,setOptionThree]=useState("");
let params=useParams()
const navigate = useNavigate()
function handleQuestion(e){
e.preventDefault();
if (question ===''){
alert("please add question")
return
}
const examcollref = collection(db,`Exams/${params.id}/qna`);
addDoc(examcollref,{
question:question,
correctanswer:correctanswer,
incorrectanswer:[
optionone,
optiontwo,
optionthree
]
}).then(response => {
alert("question added")
navigate(-1)
}).catch(error =>{
console.log(error.message)
console.log(params.id)
})
}
return (
<div className="newQuestion">
<Sidebar/>
<div className="newQuestionContainer">
<Navbar/>
<div className="leftContainer">
<div className="leftTitle">
Add Question
</div>
<br />
<form onSubmit={handleQuestion}>
<label htmlFor="">Questions</label>
<input type="text"
placeholder="question"
onChange={e =>setQuestion(e.target.value)}
value={question} />
<h6>Input words for choices</h6>
<label htmlFor="">Choice A</label>
<input type="text"
placeholder='Input Choice A'
onChange={e => setOptionOne(e.target.value)}
value={optionone}/>
<label htmlFor="">Choice B</label>
<input type="text"
placeholder='Input Choice B'
onChange={e => setOptionTwo(e.target.value)}
value={optiontwo}/>
<label htmlFor="">Choice C</label>
<input type="text"
placeholder='Input Choice C'
onChange={e => setOptionThree(e.target.value)}
value={optionthree}/>
<label htmlFor="">Correct Answer</label>
<input type="text"
placeholder='Correct Answer'
onChange={e => setCorrectAnswer(e.target.value)}
value={correctanswer}/>
<button button="submit">Add</button>
</form>
</div>
</div>
</div>
)
}
export default NewQuestion
[enter image description here][1]
this is the model of my collection now. i want to get the questions and choices to post on my manageexam.jsx note that the choices are arrays.
manageexam.jsx
import React, { useEffect, useState , useRef} from 'react'
import Sidebar from '../../components/sidebar/Sidebar'
import Navbar from '../../components/navbar/Navbar'
import "./manageExam.scss"
import { Examtable } from "../../components/datatable/Examtable"
import { getDocs, getDoc , collection , onSnapshot, deleteDoc,updateDoc, doc,where,query,orderBy} from '#firebase/firestore'
import { db } from '../../firebase'
import {Link} from "react-router-dom"
import { useParams } from 'react-router-dom';
const ManageExam = () => {
const {id}=useParams()
const isMounted = useRef()
const [description,setDesc]=useState("")
const [title,setTitle]=useState("")
const [questions,setquestions] = useState("")
const [choice, setChoices] = useState("")
// const [currentId,setCurrentId]=useState([])
// const collectionRef = collection(db, "qna",id)
function handleUpdate(e){
e.preventDefault();
const examcollref = doc(db,"Exams",id)
updateDoc(examcollref,{
title:title,
description:description
} ).then(response => {
alert("updated")
console.log(getDoc(id))
}).catch(error =>{
console.log(error.message)
})
}
const getData = () => {
const document = doc(db, "Exams", id)
onSnapshot(document, (docs) => {
setTitle(docs.data().title)
setDesc(docs.data().description)
})
}
useEffect(() => {
if(isMounted.current){
return
}
isMounted.current = true;
getData()
}, [])
//get questions and choices,
// const getDatas = () => {
// onSnapshot(collectionRef, (data) => {
// console.log(data.docs.map((doc) => {
// return {...doc.data(), id: doc.id}
// }))
// })
// }
// useEffect(() => {
// if(isMounted.current){
// return
// }
// isMounted.current = true;
// getDatas()
// }, [])
return (
<div className="manageExam">
<Sidebar/>
<div className="manageExamContainer">
<div className="examInfo">
<h1>Manage Exam</h1>
</div>
<div className="left">
<div className="leftForm">
<div className="leftTitle">
Exam information
</div>
<br />
<form action="" onSubmit={handleUpdate}>
<textarea
id="desc"
cols="30"
rows="2"
placeholder="title"
value={title}
onChange={e => setTitle(e.target.value)}
></textarea>
<textarea
id="desc"
cols="30"
rows="7"
value={description}
onChange={e => setDesc(e.target.value)}
></textarea>
<button type="submit">Update</button>
</form>
</div>
</div>
<div className="right">
<div className="rightForm">
<div className="rightTitle">
Add Questions
<Link to= {`add_question/${id}`}style={{textDecoration:"none"}} className="link" >
Add new
</Link>
</div>
THIS IS THE CONTAINER THAT I WANT TO POST
{/* <div className="rightContainer">
{questions.map((doc) => {
return (
<div>
<p>{doc.questions}</p>
</div>
)
})}
<div>
<input type="radio" name="option1" value="database" checked/>
<label htmlFor="">database</label>
</div>
<div>
<input type="radio" name="option2" value="data" disabled/>
<label htmlFor="">data</label>
</div>
<div>
<input type="radio" name="option3" value="databytes" disabled/>
<label htmlFor="">databytes</label>
</div>
<div>
<input type="radio" name="option4" value="databoard" disabled/>
<label htmlFor="">databoard</label>
</div>
<br />
<button>update</button>
<button>delete</button>
</div> */}
</div>
</div>
</div>
</div>
)
}
export default ManageExam
this is what my database look like
[1]: https://i.stack.imgur.com/CgQTC.png
I need to make a login page, when I click the submit button this should be navigated to Dashboard page. The below is my code, what is the problem in it. When I give details in the login page and click on login, the details vanishes and not navigated to dashboard.
import React, { Component, useState } from "react";
import axios from 'axios';
import { setUserSession } from '../utils/common';
function Login(props) {
const username = useFormInput('');
const password = useFormInput('');
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
// handle button click of login form
const handleLogin = () => {
props.history.push('/dashboard');
}
return (
<form>
<h3>Sign In</h3>
<div className="form-group">
<label>Email address</label>
<input type="email" className="form-control" placeholder="Enter email" />
</div>
<div className="form-group">
<label>Password</label>
<input type="password" className="form-control" placeholder="Enter password" />
</div>
<div className="form-group">
<div className="custom-control custom-checkbox">
<input type="checkbox" className="custom-control-input" id="customCheck1" />
<label className="custom-control-label" htmlFor="customCheck1">Remember me</label>
</div>
</div>
{error && <><small style={{ color: 'red' }}>{error}</small><br /></>}<br />
<input type="button" className="btn btn-primary btn-block" value={loading ? 'Loading...' : 'Sign-in'} onClick={handleLogin} disabled={loading} /><br />
<p className="forgot-password text-right">
Forgot password?
</p>
</form>
);
}
const useFormInput = initialValue => {
const [value, setValue] = useState(initialValue);
const handleChange = e => {
setValue(e.target.value);
}
return {
value,
onChange: handleChange
}
}
export default Login;
Do you have a route defined for /dashboard. Everything worked me in code sandbox without react router setup. Psuedo code shown below
<Switch>
<Route path="/dashboard">
<DashboardComponent />
</Route>
</Switch>