reactjs how to get previous user detail with html select? - html

I'm new to react, and looks like I'm following the tutorial with an old version of react. So, I have some users with their role, and the problem is when I want to make changes to the user role I want it to select the previous user role for preview (not the default value, in this case "admin").
userEdit.tsx
import axios from "axios";
import React, { SyntheticEvent, useEffect, useState } from "react";
import { Navigate, useParams } from "react-router-dom";
import Wrapper from "../../components/Wrapper";
import { Role } from "../../models/role";
const UserEdit = (props: any) => {
const [first_name, setFirstName] = useState('');
const [last_name, setLastName] = useState('');
const [email, setEmail] = useState('');
const [role_id, setRoleId] = useState('');
const [roles, setRoles] = useState([]);
const [redirect, setRedirect] = useState(false);
const {id} = useParams();
useEffect(() => {
(
async () => {
const response = await axios.get('roles');
setRoles(response.data);
const {data} = await axios.get(`users/${id}`);
setFirstName(data.first_name);
setLastName(data.last_name);
setEmail(data.email);
setRoleId(data.role_id);
}
)()
}, [id]);
const submit = async (e: SyntheticEvent) => {
e.preventDefault();
await axios.put(`users/${id}`, {
first_name,
last_name,
email,
role_id
});
setRedirect(true)
}
if(redirect) {
return <Navigate to="/users"/>
}
return (
<Wrapper>
<form onSubmit={submit}>
<h1 className="h3 mb-3 fw-normal">Edit user</h1>
<div className="form-floating">
<input className="form-control" placeholder="First Name" defaultValue={first_name} onChange={e => setFirstName(e.target.value)} required/>
<label htmlFor="floatingInput">First Name</label>
</div>
<div className="form-floating">
<input className="form-control" placeholder="Last Name" defaultValue={last_name} onChange={e => setLastName(e.target.value)} required/>
<label htmlFor="floatingInput">Last Name</label>
</div>
<div className="form-floating">
<input type="email" className="form-control" placeholder="Email Address" defaultValue={email} onChange={e => setEmail(e.target.value)} required/>
<label htmlFor="floatingInput">Email Address</label>
</div>
<div className="form-floating">
<select className="form-control" value={role_id} onChange={e => setRoleId(e.target.value)}>
{roles.map((r: Role) => {
return (
<option key={r.id} value={r.id}>{r.name}</option>
)
})}
</select>
<label>Role</label>
</div>
<button className="w-100 btn btn-lg btn-primary" type="submit">Save</button>
</form>
</Wrapper>
);
};
export default UserEdit;
As you can see I'm using "value={role_id}" to get the previous user role, but it seems to not be working. Please help me so I can continue the tutorial.

try setting defaultValue = {role_id} instead of value

Related

React - HTML form validation doesn't work

I work on a React project. I wrote HTML codes for create form. There is validation in HTML scripts. I wrote validations but validations doesn't work. The code is below. For example I want the relevant field to be red when the name is not entered or I want it to give a warning message when the name does not comply with the text rules. I must do it without any library. How can I fix it ?
import React, { Component } from 'react'
import EmployeeService from '../services/EmployeeService';
class CreateEmployeeComponent extends Component {
constructor(props) {
super(props)
this.state = {
id: this.props.match.params.id,
firstName: '',
lastName: '',
emailId: ''
}
}
componentDidMount(){
if(this.state.id === '_add'){
return
}else{
EmployeeService.getEmployeeById(this.state.id).then( (res) =>{
let employee = res.data;
this.setState({firstName: employee.firstName,
lastName: employee.lastName,
emailId : employee.emailId
});
});
}
}
saveOrUpdateEmployee = (e) => {
e.preventDefault();
let employee = {firstName: this.state.firstName, lastName: this.state.lastName, emailId: this.state.emailId};
console.log('employee => ' + JSON.stringify(employee));
// step 5
if(this.state.id === '_add'){
EmployeeService.createEmployee(employee).then(res =>{
this.props.history.push('/employees');
});
}else{
EmployeeService.updateEmployee(employee, this.state.id).then( res => {
this.props.history.push('/employees');
});
}
}
changeFirstNameHandler= (event) => {
this.setState({firstName: event.target.value});
}
changeLastNameHandler= (event) => {
this.setState({lastName: event.target.value});
}
changeEmailHandler= (event) => {
this.setState({emailId: event.target.value});
}
cancel(){
this.props.history.push('/employees');
}
getTitle(){
if(this.state.id === '_add'){
return <h3 className="text-center">Add Employee</h3>
}else{
return <h3 className="text-center">Update Employee</h3>
}
}
onSubmit = e => {
e.preventDefault();
}
render() {
return (
<div>
<br></br>
<div className = "container">
<div className = "row">
<div className = "card col-md-6 offset-md-3 offset-md-3">
{
this.getTitle()
}
<div className = "card-body">
<form onSubmit={this.onSubmit} noValidate>
<div className = "form-group">
<label for="validationCustom01" class="form-label">First name</label>
<input type='text' maxLength={20} pattern='[A-Za-z]' placeholder="First Name" name="firstName" className="form-control"
value={this.state.firstName} onChange={this.changeFirstNameHandler} required/>
</div>
<div className = "form-group">
<label> Last Name: </label>
<input type='text' maxLength={20} pattern='[A-Za-z]'class="form-control" placeholder="Last Name" name="lastName" className="form-control"
value={this.state.lastName} onChange={this.changeLastNameHandler} required/>
</div>
<div className = "form-group">
<label> Email Id: </label>
<input type='email' maxLength={35} pattern='[A-Za-z]' placeholder="Email Address" name="emailId" className="form-control"
value={this.state.emailId} onChange={this.changeEmailHandler} required/>
</div>
<button type="submit" className="btn btn-success" onClick={this.saveOrUpdateEmployee}>Save</button>
<button className="btn btn-danger" onClick={this.cancel.bind(this)} style={{marginLeft: "10px"}}>Cancel</button>
</form>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default CreateEmployeeComponent
Remove noValidate from your <form> element.
Additionally, I've personally found that Formik and Yup can be a helpful library.
(Sorry I missed that "no libraries" wasa constraint)
Edit:
I was a muppet and forgot to change the pattern
You can do one of 2 things:
Remove maxLength and change the pattern to pattern="[A-Za-z]{1,20}"
Where 20 will be the new max-length (so 20 or 35, depending on the field)
Only change the pattern to be pattern="[A-Za-z]+"
The + is needed to ensure 1 or more of the [A-Za-z] regex is done. https://regexr.com/
Also don't forget to remove noValidate from your <form> element.
This answer may also prove helpful in setting custom validity status messages and callbacks.

Failed to create check box preview using defaultChecked in reactjs

I'am new using reactjs and looks like I am following the tutorial with old version of react. So, I have some roles with their permissions, the problem is when I want to make changes of the role permissions I need to preview them with previous checked permission. As you can see the image below I have the permissions data, but when I try to put them into checkbox using default checked there is nothing happen.
here is my code
RoleEdit.tsx
import axios from "axios";
import { SyntheticEvent, useEffect, useState } from "react";
import { Navigate, useParams } from "react-router-dom";
import Wrapper from "../../components/Wrapper";
import { Permission } from "../../models/permissions";
const RoleEdit = (props:any) => {
const [permissions, setPermissions] = useState([]);
const [selected, setSelected] = useState([] as number[]);
const [name, setName] = useState('');
const [redirect, setRedirect] = useState(false);
const {id} = useParams();
useEffect( () => {
(
async () => {
const response = await axios.get('permissions');
setPermissions(response.data);
const {data} = await axios.get(`roles/${id}`);
setName(data.name);
setSelected(data.permissions.map((p : Permission) => p.id));
}
)();
}, [id]);
const check = (id: number) => {
if(selected.some(s => s === id)){
setSelected(selected.filter(s => s !== id));
return;
}
setSelected([...selected, id]);
}
const submit = async (e: SyntheticEvent) => {
e.preventDefault();
await axios.post('roles', {
name,
permissions: selected
});
setRedirect(true);
}
if(redirect){
return <Navigate to="/roles"/>
}
return(
<Wrapper>
<form onSubmit={submit}>
<div className="mb-3 mt-3 row">
<label className="col-sm-2 col-form-label">Role Name</label>
<div className="col-sm-10">
<input className="form-control" defaultValue={name} onChange={e => setName(e.target.value)}/>
</div>
</div>
<div className="mb-3 row">
<label className="col-sm-2 col-form-label">Permissions</label>
<div className="col-sm-10">
{permissions.map((p: Permission) => {
return(
<div className="form-check form-check-inline col-3" key={p.id}>
<input className="form-check-input" type={"checkbox"}
value={p.id}
defaultChecked={selected.some( s => s === p.id)}
onChange={()=> check(p.id)}/>
<label className="form-check-label">{p.name}</label>
</div>
)
})}
</div>
</div>
<button className="w-100 btn btn-lg btn-primary" type="submit">Save</button>
</form>
</Wrapper>
);
};
export default RoleEdit;
please help me solve the problem so I can continue the tutorial. Thankyou

Nodejs- How to save my file/ file name to mysql database

I am trying to save a photo to my database. I have implemented the multer middelware to upload the file to my server. I have a folder called uploads where I am storing my photo. I have successfully renamed the file in my backend with the extension and I am able to get the file in my uploads folder. However, the challenge I am now facing is saving the file name/ file path to mysql database so that I can retrieve it again in my front-end.
editUser.js (front-end form):
import axios from "axios";
import { React, useState, useEffect } from "react";
import { useHistory, withRouter } from "react-router-dom";
function UserMaster_Edit(props) {
const [CmpnyCode, setCmpnyCode] = useState("");
const [UserID, setUserID] = useState("");
const [UserFullName, setUserFullName] = useState("");
const [UserDetail, setUserDetail] = useState("");
const [LoginID, setLoginID] = useState("");
const [Password, setPassword] = useState("");
const [UserPin, setUserPin] = useState("");
const [UserEmailID, setUserEmailID] = useState("");
const [UserFP, setUserFP] = useState({});
const [Photo, setPhoto] = useState({});
const [IsActive, setIsActive] = useState("");
const [LicCount, setLicCount] = useState("");
const [DateCreated, setDateCreated] = useState("");
const [CreatedBy, setCreatedBy] = useState("");
const [RecordChanged, setRecordChanged] = useState("");
const [LocationID, setLocationID] = useState("");
const [isValid, setisValid] = useState("");
const [isDeleted, setisDeleted] = useState("");
const history = useHistory();
const argu = props.match.params.UserID;
useEffect(() => {
axios.get("http://localhost:8000/getuserid/" + argu).then((response) => {
setCmpnyCode(response.data[0].CmpnyCode);
setUserID(response.data[0].UserID);
setUserFullName(response.data[0].UserFullName);
setUserDetail(response.data[0].UserDetail);
setLoginID(response.data[0].LoginID);
setPassword(response.data[0].Password);
setUserPin(response.data[0].UserPin);
setUserEmailID(response.data[0].UserEmailID);
setUserFP(response.data[0].UserFP);
//setPhoto(response.data[0].Photo);
setIsActive(response.data[0].IsActive.data[0]);
setLicCount(response.data[0].LicCount);
setDateCreated(response.data[0].DateCreated);
setCreatedBy(response.data[0].CreatedBy);
setRecordChanged(response.data[0].RecordChanged.data[0]);
setLocationID(response.data[0].LocationID);
setisValid(response.data[0].isValid);
setisDeleted(response.data[0].isDeleted);
});
}, [argu]);
const editData = () => {
axios.put("http://localhost:8000/upusermst/" + argu, {
CmpnyCode,
UserID,
UserFullName,
UserDetail,
LoginID,
Password,
UserPin,
UserEmailID,
UserFP,
// Photo,
IsActive,
LicCount,
DateCreated,
CreatedBy,
RecordChanged,
LocationID,
isValid,
isDeleted,
});
history.push("/usermst");
};
const uploadPhoto = (event, argu) => {
event.preventDefault();
const formData = new FormData();
formData.append("avatar", Photo);
fetch("http://localhost:8000/uploadphoto/" + argu, {
method: "PUT",
body: formData,
});
};
return (
<div className="App">
<div className="auth-wrapper">
<div className="auth-inner">
<form enctype="multipart/form-data">
<h3> Edit User Master</h3>
<div>
<div className="form-class8">
<div className="form-group">
<label>Company Code</label>
<input
type="text"
className="form-control"
placeholder="CompanyCode"
value={CmpnyCode}
onChange={(e) => {
setCmpnyCode(e.target.value);
}}
name="CmpnyCode"
/>
</div>
<div className="form-group">
<label>UserID</label>
<input
type="text"
className="form-control"
placeholder="UserID"
value={UserID}
onChange={(e) => {
setUserID(e.target.value);
}}
name="UserID"
/>
</div>
<div className="form-group">
<label>UserFullName</label>
<input
type="text"
className="form-control"
placeholder="UserFullName"
value={UserFullName}
onChange={(e) => {
setUserFullName(e.target.value);
}}
name="UserFullName"
/>
</div>
<div className="form-group">
<label>UserDetail</label>
<input
type="text"
className="form-control"
placeholder="UserDetail"
onChange={(e) => {
setUserDetail(e.target.value);
}}
name="UserDetail"
value={UserDetail}
/>
</div>
<div className="form-group">
<label>LoginID</label>
<input
type="text"
className="form-control"
placeholder="LoginID"
onChange={(e) => {
setLoginID(e.target.value);
}}
name="LoginID"
value={LoginID}
/>
</div>
<div className="form-group">
<label>Password</label>
<input
type="text"
className="form-control"
placeholder="Password"
onChange={(e) => {
setPassword(e.target.value);
}}
name="Password"
value={Password}
/>
</div>
<div className="form-group">
<label>UserPin</label>
<input
type="text"
className="form-control"
placeholder="UserPin"
onChange={(e) => {
setUserPin(e.target.value);
}}
name="UserPin"
value={UserPin}
/>
</div>
<div className="form-group">
<label>UserEmailID</label>
<input
type="email"
className="form-control"
placeholder="UserEmailID"
onChange={(e) => {
setUserEmailID(e.target.value);
}}
name="UserEmailID"
value={UserEmailID}
/>
</div>
</div>
<div className="form-class8">
<div className="form-group">
<label>UserFP</label>
<input
type="file"
className="form-control"
placeholder="UserFP"
onChange={(e) => {
setUserFP(e.target.value);
}}
name="UserFP"
/>
</div>
<div className="form-group">
<label>Photo</label>
<input
type="file"
className="form-control"
placeholder="Photo"
onChange={(e) => {
setPhoto(e.target.files[0]);
}}
id="Photo"
name="Photo"
/>
<button onClick={(event) => uploadPhoto(event)}>
Upload
</button>
</div>
<div className="form-group">
<label>IsActive</label>
<input
type="text"
className="form-control"
placeholder="IsActive"
onChange={(e) => {
setIsActive(e.target.value);
}}
name="IsActive"
value={IsActive}
/>
</div>
<div className="form-group">
<label>LicCount</label>
<input
type="text"
className="form-control"
placeholder="LicCount"
onChange={(e) => {
setLicCount(e.target.value);
}}
name="LicCount"
value={LicCount}
/>
</div>
<div className="form-group">
<label>DateCreated</label>
<input
type="text"
className="form-control"
placeholder="DateCreated"
onChange={(e) => {
setDateCreated(e.target.value);
}}
name="DateCreated"
value={DateCreated}
/>
</div>
<div className="form-group">
<label>CreatedBy</label>
<input
type="text"
className="form-control"
placeholder="CreatedBy"
onChange={(e) => {
setCreatedBy(e.target.value);
}}
name="CreatedBy"
value={CreatedBy}
/>
</div>
<div className="form-group">
<label>RecordChanged</label>
<input
type="text"
className="form-control"
placeholder="RecordChanged"
onChange={(e) => {
setRecordChanged(e.target.value);
}}
name="RecordChanged"
value={RecordChanged}
/>
</div>
<div className="form-group">
<label>LocationID</label>
<input
type="text"
className="form-control"
placeholder="LocationID"
onChange={(e) => {
setLocationID(e.target.value);
}}
name="LocationID"
value={LocationID}
/>
</div>
</div>
<div className="form-class8">
<div className="form-group">
<label>isValid</label>
<input
type="date"
className="form-control"
placeholder="isValid"
onChange={(e) => {
setisValid(e.target.value);
}}
name="isValid"
value={isValid}
/>
</div>
<div className="form-group">
<label>isDeleted</label>
<input
type="date"
className="form-control"
placeholder="isDeleted"
onChange={(e) => {
setisDeleted(e.target.value);
}}
name="isDeleted"
value={isDeleted}
/>
</div>
</div>
<button
className="btn btn-primary btn-block"
onClick={() => editData()}
>
Edit
</button>
</div>
</form>
</div>
</div>
</div>
);
}
export default withRouter(UserMaster_Edit);
I am trying to work with the "Photo" div here
index.js:
const multer = require("multer");
const fs = require("fs");
const upload = multer({ dest: "uploads/" });
app.put("/uploadphoto/:UserId", upload.single("avatar"), (req, res) => {
const userid = req.params.userId;
const photo = req.file;
const fileType = photo.mimetype.split("/")[1];
let newFileName = photo.filename + "." + fileType;
fs.rename(
`./uploads/${photo.filename}`,
`./uploads/${newFileName}`,
function () {
console.log("file renamed and uploaded");
}
);
console.log(photo);
console.log("fileName ", newFileName);
db.query(
"UPDATE usermst SET Photo=? WHERE UserID=?",
[newFileName, userid],
(err, result) => {
console.log(err);
res.json({ result });
}
);
});
I just realized what the problem here was. A very minute detail.
In the upload photo function, I am passing two arguments; event and argu.
Argu is undefined hence ther is no userID being passed, it is undefined too.
The function should look like this:
const uploadPhoto = (event) => {
event.preventDefault();
const formData = new FormData();
formData.append("avatar", Photo);
fetch("http://localhost:8000/uploadphoto/" + argu, {
method: "PUT",
body: formData,
});
};```
This should pass the correct userID and update the database as well.

Trying to add scroll event listener on window, but getting Uncaught TypeError: Cannot read property 'classList' of null

I am trying to add the bottom shadow to the search bar on scroll in react js. it is working well until I go on the second page of my app.
When I am trying to go on the second page, it showing
Uncaught TypeError: Cannot read property 'classList' of null
Not working code :
import React, { useEffect } from 'react';
import { AiOutlineSearch } from "react-icons/ai";
const SearchBar = ({ totalPrograms, programs, setPrograms }) => {
const handleScroll = () => {
if(window.scrollY) {
document.getElementById('sb-header').classList.add('h-shadow');
}
else {
document.getElementById('sb-header').classList.remove('h-shadow');
}
}
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => {window.removeEventListener('scroll', handleScroll)};
},[]);
const handleSubmit = (event) => {
event.preventDefault();
const searchProgramName = document.getElementById('search').value;
if(searchProgramName) {
setPrograms(
programs.filter(program =>
program.name.toLowerCase().includes(searchProgramName)
)
);
}
else {
handleClick();
}
}
const handleClick = () => {
const allPhase = document.getElementsByName('phase');
const checkedPhaseValue = [];
allPhase.forEach(phase => {
if(phase.checked) {
checkedPhaseValue.push(phase.value);
}
});
setPrograms(checkedPhaseValue.length ?
totalPrograms.filter(
program => checkedPhaseValue.includes(program.phase.toLowerCase())
)
: totalPrograms
);
}
return (
<header id='sb-header' className="container header-sb">
<form className="container container-center" onSubmit={handleSubmit}>
<div className="type-search">
<AiOutlineSearch className="icon"/>
<input id="search" type="search" placeholder="search by program name"/>
</div>
<div className="checkbox-container">
<div className="d-inline">
<input type="checkbox" onClick={handleClick} name="phase" id="open_application" value="application_open"/>
<label htmlFor="open_application">Open Application</label>
</div>
<div className="d-inline">
<input type="checkbox" onClick={handleClick} name="phase" id="application_in_review" value="application_review"/>
<label htmlFor="application_in_review">Application in Review</label>
</div>
<div className="d-inline">
<input type="checkbox" onClick={handleClick} name="phase" id="in_progress" value="in_progress"/>
<label htmlFor="in_progress">in Progress</label>
</div>
<div className="d-inline">
<input type="checkbox" onClick={handleClick} name="phase" id="completed" value="completed"/>
<label htmlFor="completed">Completed</label>
</div>
</div>
</form>
</header>
)
}
export default SearchBar;
On the second page, I am going by clicking on the Details button. Code for that :
import React from 'react';
import { Link } from 'react-router-dom';
import { FaAngleDoubleRight } from 'react-icons/fa';
import * as ROUTES from '../Constants/routes';
const ProgramCards = ({ program }) => {
return (
<div className="card">
<div className="card-header">
<h1 className="p-name">{program.name}</h1>
</div>
<div className="card-body">
<h3 className="p-category">{program.category}</h3>
<small className="p-phase">{(program.phase).replace('_', ' ')}</small>
<p className="p-description">{program.shortDescription}</p>
</div>
<div>
<div className="date-duration">
<small className="p-date">Start Date: {program.startDate}</small>
<small className="p-duration">Duration: {program.duration}</small>
</div>
<Link to={ROUTES.PROGRAM_DETAILS}>
<button className="card-button">
Details <FaAngleDoubleRight className="icon angled-icon" />
</button>
</Link>
</div>
</div>
)
}
export default ProgramCards;
My question is, why it is not working?
After this, I tried a different approach. And it is working well.
Working code :
import React, { useEffect, useState } from 'react';
import { AiOutlineSearch } from "react-icons/ai";
const SearchBar = ({ totalPrograms, programs, setPrograms }) => {
const [ scrolled, setScrolled ] = useState(false);
const handleScroll = () => {
if(window.scrollY > 10) {
setScrolled(true);
}
else {
setScrolled(false);
}
}
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => {window.removeEventListener('scroll', handleScroll)};
},[]);
const handleSubmit = (event) => {
event.preventDefault();
const searchProgramName = document.getElementById('search').value;
if(searchProgramName) {
setPrograms(
programs.filter(program =>
program.name.toLowerCase().includes(searchProgramName)
)
);
}
else {
handleClick();
}
}
const handleClick = () => {
const allPhase = document.getElementsByName('phase');
const checkedPhaseValue = [];
allPhase.forEach(phase => {
if(phase.checked) {
checkedPhaseValue.push(phase.value);
}
});
setPrograms(checkedPhaseValue.length ?
totalPrograms.filter(
program => checkedPhaseValue.includes(program.phase.toLowerCase())
)
: totalPrograms
);
}
return (
<header className={`container header-sb ${scrolled && 'h-shadow'}`}>
<form className="container container-center" onSubmit={handleSubmit}>
<div className="type-search">
<AiOutlineSearch className="icon"/>
<input id="search" type="search" placeholder="search by program name"/>
</div>
<div className="checkbox-container">
<div className="d-inline">
<input type="checkbox" onClick={handleClick} name="phase" id="open_application" value="application_open"/>
<label htmlFor="open_application">Open Application</label>
</div>
<div className="d-inline">
<input type="checkbox" onClick={handleClick} name="phase" id="application_in_review" value="application_review"/>
<label htmlFor="application_in_review">Application in Review</label>
</div>
<div className="d-inline">
<input type="checkbox" onClick={handleClick} name="phase" id="in_progress" value="in_progress"/>
<label htmlFor="in_progress">in Progress</label>
</div>
<div className="d-inline">
<input type="checkbox" onClick={handleClick} name="phase" id="completed" value="completed"/>
<label htmlFor="completed">Completed</label>
</div>
</div>
</form>
</header>
)
}
export default SearchBar;
Your second approach is the better and the react way to do it. It is generally discouraged to query the DOM managed by react yourself. Use ref's if you need the DOM node.
The first example is not working because handleScroll will be recreated every time the component re-renders. Therefore removing the listener will not remove the original listener as the function referenced by handleScroll has changed.
Therefore when your component unmounts the listener will not be removed correctly but react will remove the DOM node. Next time you scroll the handler will still be called but the node you are trying to query isn't there anymore.
You have to create the listener inside of useEffect so that your removeEventListener references the correct function:
useEffect(() => {
const handleScroll = () => setScrolled(window.scrollY > 10);
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
},[]);
Alternatively you could use useRef to create a stable reference to you listener function.

show login page for a second when routering other pages reactJS

I use this video https://www.youtube.com/watch?v=r4EsP6rovwk&t=1s to create an Auth for my website,
i basically copied his code the only change is that I route after successful login to different page.
the problem is that after login my home page is shown, but when I'm pressing buttons to route for other pages, before the other page is shown I see for a second the login page.
this is the code of the auth - I believe it connect to the problem (before this my website has worked well).
Edit:
i try to figure out what's the problem and I've noticed that when i'm using link everything's fine, but when using href there's a problem.
(And that's what I did in my website).
So... does anyone know why href makes this issue?
app.js
import React, { Component } from 'react';
import fire from './Fire';
import SearchAppBar from '../components/appBar';
import Login from './login';
class App extends Component {
constructor() {
super();
this.state = ({
user: null,
});
this.authListener = this.authListener.bind(this);
}
componentDidMount() {
this.authListener();
}
authListener() {
fire.auth().onAuthStateChanged((user) => {
if (user) {
this.setState({ user });
} else {
this.setState({ user: null });
}
});
}
render() {
return (
<div>{this.state.user ? ( <SearchAppBar/>) : (<Login />)}</div>)
}
}
export default App;
login.js:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import fire from './Fire';
class Login extends Component {
constructor(props) {
super(props);
this.login = this.login.bind(this);
this.handleChange = this.handleChange.bind(this);
this.signup = this.signup.bind(this);
this.state = {
email: '',
password: ''
};
}
handleChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
login(e) {
e.preventDefault();
fire.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then((u)=>{
}).catch((error) => {
console.log(error);
});
}
signup(e){
e.preventDefault();
fire.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).then((u)=>{
}).then((u)=>{console.log(u)})
.catch((error) => {
console.log(error);
})
}
render() {
return (
<div className="col-md-6">
<form>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input value={this.state.email} onChange={this.handleChange} type="email" name="email"
class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter
email" />
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.
</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input value={this.state.password} onChange={this.handleChange} type="password" name="password"
class="form-control" id="exampleInputPassword1" placeholder="Password" />
</div>
<button type="submit" onClick={this.login} className="btn btn-primary">Login</button>
<button onClick={this.signup} style={{marginLeft: '25px'}} className="btn btn-
success">Signup</button>
</form>
</div>
);
}
}
export default Login;
Thank you all guys!!