Reactjs setEmail is not a function onChange although it is function - reactjs

It gives an error i do not know why, If you look my codes, there is not any problem you will see.
Login Route page:
const [email, setEmail] = useState("");
<LoginPage
email={email}
setEmail={setEmail} />
Login Form codes:
const {
email,
setEmail,
} = props;
<input
type="email"
className="form-control"
placeholder="Enter email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>

Login Page Component
<LoginPage />
Login Form Component
import React, { useState } from "react";
const LoginForm = (props) => {
const [email, setEmail] = useState("");
return (
<>
<input
type="email"
className="form-control"
placeholder="Enter email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
{/* Other components */}
</>
);
};

Related

React testing library - Property 'value' does not exist on type 'HTMLElement'

I have a super simple form I'm trying to test with react testing library
The form is like
import React, { useState } from 'react';
import './App.css';
function App() {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
return (
<div className="App">
<form>
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
name="email"
value={email}
onChange={e => setEmail(e.target.value)}
/>
<label htmlFor="password">Password</label>
<input
type="password"
id="password"
name="password"
value={password}
onChange={e => setPassword(e.target.value)}
/>
</form>
</div>
);
}
export default App;
And simple trying to test the input with
test('should be able to type an email', () => {
render(<App />)
const emailInput = screen.getByRole('textbox', {name: /email/i})
userEvent.type(emailInput, 'test#email.com')
expect(emailInput.value).toBe('test#email.com')
})
But this errors at emailInput.value saying
Property 'value' does not exist on type 'HTMLElement'.
I'm using typescript in the app, is this to do with types. How can I fix this
const emailInput = screen.getByRole<HTMLInputElement>('textbox', {name: /email/i}) should work in your case

Conditional statement to show registration success message is showing the error message even when successful?

I wasn't sure how to phrase the title but basically, I am following a tutorial to create a login/registration and I am currently trying to display a message indicating whether the registration attempt was successful or not.
Here is my Register.js
import React, { useState } from 'react';
import { Form, Button } from 'react-bootstrap';
import axios from "axios";
export default function Register() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [register, setRegister] = useState(false);
const handleSubmit = (e) => {
// prevent the form from refreshing the whole page
e.preventDefault();
//set configuration
const configuration = {
method: "post",
url: "https://nodejs-mongodb-auth-app-learn.herokuapp.com/register",
data: {
email,
password,
},
};
// API call
axios(configuration)
.then((result) => {
console.log(result);
setRegister=(true);
})
.catch((error) => {
error= new Error;
})
};
return (
<>
<h2>Register</h2>
<Form onSubmit={(e)=>handleSubmit(e)}>
{/* email */}
<Form.Group controlId="formBasicEmail">
<Form.Label>Email Address</Form.Label>
<Form.Control
type="email"
name="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Enter email"
/>
</Form.Group>
{/* password */}
<Form.Group controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
name="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter password"
/>
</Form.Group>
{/* submit button */}
<Button
variant="primary"
type="submit"
onClick={(e)=>handleSubmit(e)}
>
Register
</Button>
{/* display success message */}
{register ? (
<p className="text-success">You Are Registered Successfully</p>
) : (
<p className="text-danger">You Are Not Registered</p>
)}
</Form>
</>
)
};
The successful registration will log on the console, but either setRegister is not updating register to true, or my conditional statement is incorrect in some way?
It always shows "You Are Not Registered".
The correct way to ser an state using useState hook is:
e.g
const [register, setRegister] = useState(false);
setRegister(true)

Internal server error when attempting to register user in React/Redux app

I have a database on AtlasDB cloud service. In my React application, I want my code to save the data from the form below to be saved in the database, however I get internal server error (500) when I make a post request. What could be the problem here? The code of the React component is as follows:
import React, { useState, useEffect } from "react";
//state for form fields
import { Link } from "react-router-dom";
import { Form, Button, Row, Col } from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";
import Message from "../components/Message";
import Loader from "../components/Loader";
import FormContainer from "../components/FormContainer";
import { register } from "../actions/userActions";
const RegisterScreen = ({ location, history }) => {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [message, setMessage] = useState(null);
const dispatch = useDispatch();
const userRegister = useSelector((state) => state.userLogin);
const { loading, error, userInfo } = userRegister;
const redirect = location.search ? location.search.split("=")[1] : "/";
const goToLoginScreen = () => {
history.goBack();
}
useEffect(() => {
if (userInfo) {
history.push(redirect);
}
}, [history, userInfo, redirect]);
const submitHandler = (e) => {
e.preventDefault();
//dispatch register
if(password !== confirmPassword){
setMessage('Passwords do not match');
} else {
goToLoginScreen();
dispatch(register(name, email, password));
}
};
return (
<FormContainer>
<h1>Sign Up</h1>
{message && <Message variant="danger">{message}</Message>}
{error && <Message variant="danger">{error}</Message>}
{loading && <Loader />}
<Form onSubmit={submitHandler}>
<Form.Group controlId="name">
<Form.Label>Name </Form.Label>
<Form.Control
type="name"
placeholder="Enter name"
value={name}
onChange={(e) => setName(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group controlId="email">
<Form.Label>Email Address</Form.Label>
<Form.Control
type="email"
placeholder="Enter email"
value={email}
onChange={(e) => setEmail(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group controlId="password">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
placeholder="Enter password"
value={password}
onChange={(e) => setPassword(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group controlId="confirmPassword">
<Form.Label>Confirm Password</Form.Label>
<Form.Control
type="password"
placeholder="Confirm password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
></Form.Control>
</Form.Group>
<Button type="submit" variant="primary">
Register
</Button>
</Form>
<Row className="py-3">
<Col>
Have an account?{" "}
<Link to={redirect ? `/login?redirect=${redirect}` : "/login"}>
Login
</Link>
</Col>
</Row>
</FormContainer>
);
};
export default RegisterScreen;
It is very difficult to me to localize the error in code, whether it is a question of front-end or back-end. The user is not saved in the remote database.

React Unfocuses Input Field When Typing

React refuses to keep focus on input field while typing.
I've tried to fix it, but was not successful. I don't understand this behaviour.
This is the component:
import React, { useState } from 'react'
import styled from 'styled-components'
const Auth = () => {
const Form = styled.form``
const InputGroup = styled.div``
const Input = styled.input``
const Button = styled.button``
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
return (
<Form>
<InputGroup>
<Input
value={email}
onChange={event => {
setEmail(event.target.value)
}}
type="email"
/>
</InputGroup>
<InputGroup>
<Input
value={password}
onChange={event => {
setPassword(event.target.value)
}}
type="password"
/>
</InputGroup>
<Button />
</Form>
)
}
export default Auth
codesandbox working example of the problem
the problem is you are defining Input component inside your function which create new element each time so your new input lost focus.
to fix problem define your component outside function.
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import styled from "styled-components";
const Form = styled.form``;
const InputGroup = styled.div``;
const Input = styled.input``;
const Button = styled.button``;
const Auth = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
return (
<Form>
<InputGroup>
<Input
value={email}
onChange={event => {
setEmail(event.target.value);
}}
type="email"
/>
</InputGroup>
<InputGroup>
<Input
value={password}
onChange={event => {
setPassword(event.target.value);
}}
type="password"
/>
</InputGroup>
<Button>press me</Button>
</Form>
);
};
function App() {
return (
<div className="App">
<Auth />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

React Hooks update props from react-redux

I am having an issue with props updating with Redux. I am using redux-promise-middleware, and am making a login request. My hook receives the initialState. I can see the dispatch and reducer are being correctly updated when I console.log in the mapStateToProps function. However, the props are never updated with redux.
const Login = (props) => {
const [email, updateEmail] = useState('')
const [password, updatePassword] = useState('')
const [firstName, updateFirstName] = useState('')
const [lastName, updateLastName] = useState('')
const [loginToggle, updateLoginToggle] = useState(true)
async function handleLogin() {
const loginInfo = {email, password}
await props.loginUser(loginInfo)
if (props.user.loggedIn) props.history.push('/dashboard');
}
return (
<div className="login-page">
<div className="login-register-container">
{ loginToggle ?(
<div className="login-container">
<h2>Login</h2>
<input placeholder='Email' value={email} onChange={e =>
updateEmail(e.target.value)} />
<input placeholder='Password' value={password} onChange={e => updatePassword(e.target.value)} />
<button onClick={handleLogin}> Login </button>
<p style={{cursor:"pointer"}} onClick={() => updateLoginToggle(false)}> need to register?</p>
</div>
):(
<div className="register-container">
<h2>Register</h2>
<input placeholder='First Name' value={firstName} onChange={e => updateFirstName(e.target.value)} />
<input placeholder='Last Name' value={lastName} onChange={e => updateLastName(e.target.value)} />
<input placeholder='Email' value={email} onChange={e => updateEmail(e.target.value)} />
<input placeholder='Password' value={password} onChange={e => updatePassword(e.target.value)} />
<button onClick={handleRegister}> Register </button>
<p style={{cursor:"pointer"}} onClick={() => updateLoginToggle(true)}> already have login?</p>
</div>
)}
</div>
</div>
)
}
function mapStateToProps(reduxState) {
console.log(reduxState)
return {
user: reduxState.user
}
};
export default connect(mapStateToProps, {loginUser, getUser})(Login)

Resources