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);
}
Related
In the browser returns the input in the list when I placed, but in the same second disappears. Until the end of the function the array is fulfill, when refresh the response the array "does" is empty.
Something is wrong and the state is not storing.
import React,{useState} from 'react';
import './App.css';
function App() {
const [text1,setText1] = useState('');
const [does,setDoes] = useState([]);
function addTodo(){
return setDoes([...does,text1]);
}
return (
<div>
<h1>To do List!</h1>
<form onSubmit={addTodo}>
<input type="text" name='text1' id='text1' placeholder='To do' onChange={(e)=>setText1(e.target.value)}/>
<button type="submit" className="submitButton">Add</button>
</form>
<ul className='todoo'>
{does.map(item => <li key={item.toString()}>{item}</li>)}
</ul>
</div>
);
}
export default App;
I expect to storage the tasks...
To not disappear when you place a text and click add use e.preventDefault()
Like this:
function App() {
const [text1, setText1] = useState("");
const [does, setDoes] = useState([]);
const addTodo = (e) => {
e.preventDefault();
return setDoes([...does, text1]);
};
return (
<div>
<h1>To do List!</h1>
<form onSubmit={(e) => addTodo(e)}>
<input
type="text"
name="text1"
id="text1"
placeholder="To do"
onChange={(e) => setText1(e.target.value)}
/>
<button
type="submit"
className="submitButton"
>
Add
</button>
</form>
<ul className="todoo">
{does.map((item) => (
<li key={item.toString()}>{item}</li>
))}
</ul>
</div>
);
}
export default App;
and if you want to keep the data in the page when you refresh it you can either use an api to store the data to a database or to use localStorage.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
As you have used the form, the page refreshed when you click the submit button. Instead of a form, you can use a div and handle the event with the click of the submit button. So you can do it this way:
...
<h1>To do List!</h1>
<div>
<input
type="text"
name="text1"
id="text1"
placeholder="To do"
onChange={(e) => setText1(e.target.value)}
/>
<button type="submit" className="submitButton" onClick={addTodo}>
Add
</button>
</div>
...
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 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;
I code with next.js a login:
import type { NextPage } from 'next'
import Head from 'next/head'
import styles from '../styles/Home.module.css'
import Router from 'next/router'
import * as React from 'react'
const Home: NextPage = () => {
const [disable, setDisable] = React.useState(false);
const loginUser = async (e: any) => {
try {
setDisable(true)
const y = (window.document.getElementById('inputUsername'))
let inputValue = window.document.getElementById('inputUsername').value
console.log(inputValue)
const resp = await fetch('/api/token/valid')
const data = await resp.json()
if (data.token) {
//Router.push('/dashboard')
setDisable(false)
}
} catch (err) {
// Handle Error Here
console.error(err);
}
};
return (
<div className={styles.container}>
<Head>
<title>Login - Uhrenlounge CMS</title>
<meta name="description" content="Generated by create next app" />
</Head>
<main className={styles.main}>
<form className="p-3 mb-2 bg-secondary text-white">
<div className="text-center">
<h1>Uhrenlounge CMS</h1>
</div>
<hr />
<div className="mb-3">
<label className="form-label">Benutzername</label>
<input
type="text"
className="form-control"
id="inputUsername"
name="inputUsername"
placeholder="Benutzername"
required
/>
</div>
<div className="mb-3">
<label className="form-label">Passwort</label>
<input type="password" className="form-control" id="inputPassword" placeholder="Passwort" />
</div>
<div className="d-grid gap-2">
<button type="button" disabled={disable} onClick={loginUser} className="btn btn-primary" id="btnLoginUser">Login</button>
</div>
</form>
</main>
</div>
)
}
export default Home
I want to get the value of inputs after the click on the button.
I try to get the value with this code:
let inputValue = window.document.getElementById('inputUsername').value
VSCode give me this error: Object is possibly 'null'.
I don't know what can i do. Does anyone have any idea or explanation how to access the value after onclick?
It's just telling you that if there is no element with id 'inputUsername' getElementById will return null instead of the value you are expecting.
You can handle or ignore that case as you see fit.
However if you really need to access dom nodes in react the right way to do it is hooks https://reactjs.org/docs/hooks-intro.html. Right now your component may not work if two exist at the same time due to the overlapping ids.
import React, { useState } from 'react'
import styled from 'styled-components'
import Title from '../Components/Title'
import { InnerLayout, MainLayout } from '../Styles/Layout'
import Button from '../Components/Button'
import { db } from '../firebase';
function Contact() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [message, setMessage] = useState("");
const [subject, setSubject] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
db.collection('mail').add({
name: name,
email: email,
subject: subject,
message: message,
})
.then(() => {
alert("Thank you for contacting. Your message has been sent successfully.");
})
.catch((err) => {
alert(err.message);
});
setName('')
setEmail('')
setSubject('')
setMessage('')
};
return (
<MainLayout>
<Title title={'Contact'} span={'Contact'} />
<ContactMain>
<InnerLayout className='contact-section'>
<div className="left-content">
<div className="contact-title">
<h4>Get In Touch</h4>
</div>
<form className="form" onSubmit={handleSubmit}>
<div className="form-field">
<label htmlFor="name">Enter Your Name</label>
<input type="text" id="name" value={name} onChange={(e) => setName(e.target.value)} />
</div>
<div className="form-field">
<label htmlFor="email">Enter Your Email</label>
<input type="email" id="email" value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
<div className="form-field">
<label htmlFor="subject">Enter Your Subject</label>
<input type="text" id="subject" value={subject} onChange={(e) => setSubject(e.target.value)} />
</div>
<div className="form-field">
<label htmlFor="text-area">Enter Your Message</label>
<textarea name="textarea" id="textarea" cols="30" rows="10" value={message} onChange={(e) => setMessage(e.target.value)}></textarea>
</div>
<div className="form-field f-button">
<Button title="Send Email" />
</div>
</form>
</div>
</InnerLayout>
</ContactMain>
</MainLayout>
)
}
I don't know why but I am not able to send the details to my firebase database. I am not able to find the issue in this code. I have copied the firebase database key and all in the firebase.js and then imported it in this contact.js and I then made the necessary changes in this. Still, I am not able to figure out the issue.
I would reset the form once the promise returned by add() is resolved.
const handleSubmit = (e) => {
e.preventDefault();
db.collection('mail').add({
name: name,
email: email,
subject: subject,
message: message,
}).then(() => {
// Reset those states here
setName('')
setEmail('')
setSubject('')
setMessage('')
alert("Thank you for contacting. Your message has been sent successfully.");
}).catch((err) => {
alert(err.message);
});
};
I guess your states are being reset to "" before the document is added as those setState methods would have ran before the doc was added.
Potentially because your button html within its the button component type is not set to 'submit' - I had the same issue I think which ended up being super simple.