retrieve store data from react redux - reactjs

I'm new to redux, I can't get data from the store.I get this message in the console:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
thank you in advance for help.
reducer
import { CONNECT_CLIENT, GET_CLIENT } from "../action/Action";
export const initialClient = {
email: "",
password: ""
}
export default function ConnectClient (state = initialClient, action= {}){
switch (action.type) {
case CONNECT_CLIENT:
console.log(action.payload);
return {
...state,
client: [action.payload]
}
case GET_CLIENT:
return {
...state,
initialClient: action.initialClient
}
default:
break;
}
}
clientService
export const ConnectClient = () =>{
const {initialClient } = useSelector(state => state)
console.log(initialClient)
const dispatch = useDispatch();
dispatch({
type: GET_CLIENT,
initialClient: initialClient
})
return new Promise((resolve, reject)=>{
axios.post('http://localhost:3000/api/client/loginClient',{
initialClient: initialClient
})
.then((response, error)=>{
if(!response || error) {
return reject(`Response rejected: ${error}`);
}
resolve(response);
})
})
}
Form connection
const Connexion = () =>{
const dispatch = useDispatch();
const [email, setEmail] = useState("")
const [password, setPassword] =useState("")
const submit=(e)=>{
e.preventDefault();
ConnectClient().then(response => console.log(response))
console.log(email)
console.log(password)
dispatch({
type: CONNECT_CLIENT,
payload: {email, password}
})
}
return (
<form className="container-connexion" model="client">
<div className="container-email-password">
<div className="email">
<label htmlFor="email">Email</label>
<input id="email" type="email" value={email} onChange={(e)=> setEmail(e.target.value)} name="email" required/>
</div>
<div className="password">
<label htmlFor="password">Mot de passe</label>
<input type="password" value={password} name="password" onChange={(e)=> setPassword(e.target.value)} required/>
</div>
</div>
<div className="container-btn-connexion">
<button className="btn-connexion" onClick={submit} >Se connecter</button>
<button className="btn-inscription">Inscription</button>
</div>
</form>
)
}

We can only call hooks inside the body of functional components, or in the body of custom hooks. Your ConnectClient function is neither of those.
One solution is calling the useDispatch and useSelector hooks in the Connexion component, and passing initialClient and dispatch to the ConnectClient function as parameters.
export const ConnectClient = (dispatch, initialClient) => {
dispatch({
type: GET_CLIENT,
initialClient: initialClient,
});
return new Promise((resolve, reject) => {
axios.post('http://localhost:3000/api/client/loginClient', {
initialClient: initialClient,
}).then((response, error) => {
if(!response || error) {
return reject(`Response rejected: ${error}`);
}
resolve(response);
});
});
};
const Connexion = () =>{
const dispatch = useDispatch();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const { initialClient } = useSelector(state => state);
const submit=(e)=>{
e.preventDefault();
ConnectClient(dispatch, initialClient).then(response => console.log(response));
dispatch({
type: CONNECT_CLIENT,
payload: {email, password}
})
}
return (
<form className="container-connexion" model="client">
<div className="container-email-password">
<div className="email">
<label htmlFor="email">Email</label>
<input id="email" type="email" value={email} onChange={(e)=> setEmail(e.target.value)} name="email" required/>
</div>
<div className="password">
<label htmlFor="password">Mot de passe</label>
<input type="password" value={password} name="password" onChange={(e)=> setPassword(e.target.value)} required/>
</div>
</div>
<div className="container-btn-connexion">
<button className="btn-connexion" onClick={submit} >Se connecter</button>
<button className="btn-inscription">Inscription</button>
</div>
</form>
);
}

Related

Firebase won't register user information

Firebase isn't registering my user's information.
I keep getting a warning saying: 'onAuthStateChanged' is defined but never used and
'user' is assigned a value but never used.
Also, when I enter the email and password it doesn't set to empty string even though I set my password and email both to ("").
import './App.css';
import { auth } from './firebase';
import { useState, useEffect } from 'react';
import {
signInWithEmailAndPassword,
onAuthStateChanged, //<-----Here's my problem
createUserWithEmailAndPassword,
} from 'firebase/auth';
function App() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [user, setUser] = useState([]); // <---------Here is the other issue
const [isSignUp, setIsSignUp] = useState(false);
useEffect(() => {
auth.onAuthStateChanged((user) => {
setUser(user);
});
});
const handleEmailChange = (e) => {
setEmail(e.target.value);
};
const handlePasswordChange = (e) => {
setPassword(e.target.value);
};
const signIn = async () => {
await signInWithEmailAndPassword(auth, email, password)
.then(() => {
setEmail('');
setPassword('');
})
.catch((error) => {
alert(error.message);
});
};
const register = async () => {
await createUserWithEmailAndPassword(auth, email, password).catch((error) =>
console.log(error.message)
);
setPassword('');
setEmail('');
};
return (
<div className="App">
{isSignUp ? (
<>
<h1>Registering...</h1>
<input
type="email"
placeholder="email"
value={email}
onChange={handleEmailChange}
/>
<input
type="password"
placeholder="password"
value={password}
onChange={handlePasswordChange}
/>
<button onClick={register}>Sign Up</button>
<button onClick={() => setIsSignUp(false)}>X</button>
</>
) : (
<>
<h1>Logging in...</h1>
<input
type="email"
placeholder="email"
value={email}
onChange={handleEmailChange}
/>
<input
type="password"
placeholder="password"
value={password}
onChange={handlePasswordChange}
/>
<button onClick={signIn}>Login</button>
<button onClick={() => setIsSignUp(true)}>Register</button>
</>
)}
</div>
);
}
export default App;
I see two mistakes.
First, you should use the modular syntax for your auth state handler:
useEffect(() => {
onAuthStateChanged((user) => { // 👈 Remove the auth. here
setUser(user);
});
});
And second, the default value of the user is an object, not an array:
const [user, setUser] = useState({});
There may be more problems, but these jumped out at me.
The actual solution to my problem was that I was in the wrong app in Firebase. Once I selected the right one from the dropdown menu it worked.

Can't verify email and password from Firebase

I'm creating a signup form and trying to get the email and password to work. When I used input and set the state with the appropriate values, it works just fine, but once I wrap the Input around my custom component its unable to get data from the component into the state and gives me an error that a user cannot be found (even if their info is in the Firebase Auth)
I need help.
Auth.js
import style from "./auth.module.css";
import { useEffect, useRef, useState } from "react";
import { useAuthState } from 'react-firebase-hooks/auth';
import { auth, signInWithEmailAndPassword, signInWithGoogle } from "../../firebase";
import { CSSTransition } from "react-transition-group";
export default function Auth() {
const [activeMenu, setActiveMenu] = useState("main");
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [user, loading, error] = useAuthState(auth);
let domNode = useClickOutside(() => {
setActiveMenu(false);
});
return (
<div className={style.container}>
<Login />
<Signup />
</div>
);
function AuthType(props) {
return (
<a
href={props.link}
className={style.menuItem}
onClick={() => props.goToMenu && setActiveMenu(props.goToMenu)}
>
{props.children}
</a>
);
}
/* I believe you've switched up the login and sign-up? */
function Login() {
return (
<CSSTransition in={activeMenu === "main"} unmountOnExit timeout={500}>
<div ref={domNode}>
<div className={style.login}>
<h1 className={style.title}>Clip It</h1>
{/* Email and Password */}
<Emailform
label="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<Passform
label="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<div className={style.button}>
<input
type="submit"
value="Login"
onClick={() => signInWithEmailAndPassword(email, password)} />
<input
type="submit"
value="Login with Google"
onClick={signInWithGoogle} />
</div>
<div className={style.text}>
<p className={style.plink}>Forgot Password</p>
<div>
Need an account?
<AuthType goToMenu="Signup">click here</AuthType>
</div>
</div>
</div>
</div>
</CSSTransition>
);
}
function Signup() {
return (
<CSSTransition in={activeMenu === "Signup"} unmountOnExit timeout={500}>
<div ref={domNode}>
<div className={style.signUp}>
<div className={style.title}> Clip It</div>
<Form label="First Name" type="text" />
<Form label="Last Name" type="Text" />
<Form label="Email" type="email" />
<Form label="Date of Birth" type="date" />
<Form label="Password" type="password" />
<Form label="Confirm Password" type="password" />
<div className={style.button}>
<input type="submit" value="Sign Up" />
</div>
<div className={style.text}>
have an
<AuthType goToMenu="main"> account</AuthType>
</div>
</div>
</div>
</CSSTransition>
);
}
}
let useClickOutside = (handler) => {
let domNode = useRef();
useEffect(() => {
let clickListener = (event) => {
if (domNode.current && !domNode.current.contains(event.target)) {
handler();
}
};
document.addEventListener("mousedown", clickListener);
return () => {
document.removeEventListener("mousedown", clickListener);
};
});
return domNode;
};
function Form(props) {
return (
<div className={style.formBox}>
<label className={style.label}>{props.label}:</label>
<form className={style.input}>
<input
type={props.input}
name={props.input}
required="true" />
</form>
</div>
);
}
function Emailform(props) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
return (
<div className={style.formBox}>
<label className={style.label}>{props.label}:</label>
<form className={style.input}>
<input
type="email"
name={props.input}
required="true"
value={email}
onChange={(e) => setEmail(e.target.value)} />
</form>
</div>
);
}
function Passform(props) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
return (
<div className={style.formBox}>
<label className={style.label}>{props.label}:</label>
<form className={style.input}>
<input
type="text"
name={props.input}
required="true"
value={password}
onChange={(e) => setPassword(e.target.value)} />
</form>
</div>
);
}
Firebase.js
import firebase from 'firebase/app';
//import * as firebase from "firebase/app";
import "firebase/auth"
import "firebase/firestore"
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyCq8BAlTWJXG7rFU95QkUTU8U0kXruPA9o",
authDomain: "clip-it-70ff5.firebaseapp.com",
databaseURL: "https://clip-it-70ff5-default-rtdb.firebaseio.com",
projectId: "clip-it-70ff5",
storageBucket: "clip-it-70ff5.appspot.com",
messagingSenderId: "637963668511",
appId: "1:637963668511:web:9cbd1deae03b819153d92a",
measurementId: "G-8S1G78ZH49"
};
const app = !firebase.apps.length ? firebase.initializeApp(firebaseConfig) : firebase.app();
const auth = app.auth();
const db = app.firestore();
/* Using Google Authentication */
const googleProvider = new firebase.auth.GoogleAuthProvider();
//
const signInWithGoogle = async () => {
try {
const res = await auth.signInWithPopup(googleProvider);
const user = res.user;
const query = await db
.collection("users")
.where("uid", "==", user.uid)
.get();
if (query.docs.length === 0) {
await db.collection("users").add({
uid: user.uid,
name: user.displayName,
authProvider: "google",
email: user.email,
});
alert("You're logged in");
}
} catch (err) {
console.error(err);
alert(err.message);
}
};
/* Using Email and Password */
// Sign/Logging In
const signInWithEmailAndPassword = async (email, password) => {
try {
await auth.signInWithEmailAndPassword(email.trim(), password);
alert("You've logged in successfuly");
} catch (err) {
console.error(err);
alert("The email or password is incorrect, please try again");
}
};
//SigningUp
const registerWithEmailAndPassword = async (name, email, password) => {
try {
const res = await auth.createUserWithEmailAndPassword(email.trim(), password);
const user = res.user;
await db.collection("users").add({
uid: user.uid,
name,
authProvider: "local",
email,
});
} catch (err) {
console.error(err);
alert(err.message);
}
};
//Sending Password reset link
const sendPasswordResetEmail = async (email) => {
try {
await auth.sendPasswordResetEmail(email);
alert("Password reset link sent!");
} catch (err) {
console.error(err);
alert(err.message);
}
};
const logout = () => {
auth.signOut();
}; // Log out
export {
signInWithGoogle,
signInWithEmailAndPassword,
registerWithEmailAndPassword,
sendPasswordResetEmail,
logout,
auth,
db,
};
Your code has a list of issues.
You have email/password states in both EmailForm/PassForm, as well as the parent (Auth) component.
You're setting values and trying to handle onChange on the EmailForm/PassForm components, but you never actually call these props, and you never actually set some of the props you're trying to access (ex: name={props.input}).
The inputs inside those two components are setting the email/password states to themselves, yet your Auth component is feeding Firebase its own states for email/password, which you never actually set.
You should also never use an input of type="text" for password fields.
If you insist on keeping the structure you currently have, move the EmailForm and PassForm functions inside to your Auth component, remove the props you're setting onto them, remove their states, and just use the Auth component's state.
// Inside the Auth component
const EmailForm = () => {
return (
<div className={style.formBox}>
<label className={style.label}>{props.label}:</label>
<form className={style.input}>
<input
type="email"
name="email"
required="true"
value={email}
onChange={(e) => setEmail(e.target.value)} />
</form>
</div>
);
}
const PassForm = () => {
return (
<div className={style.formBox}>
<label className={style.label}>{props.label}:</label>
<form className={style.input}>
<input
type="password"
name="password"
required="true"
value={password}
onChange={(e) => setPassword(e.target.value)} />
</form>
</div>
);
}
Then call them with a simple
<EmailForm />
<PassForm />

Two times click is necessary to Login in ReactJS

I am trying to make a Login page and I am successful in some way. So here is my Login component:
import React, { useState, useEffect } from "react";
import Axios from "axios";
import useForm from "../components/LoginForm/useForm";
import validate from "components/LoginForm/validate";
import redtruck from "../assets/img/red-truck.png";
import auth from "../Authentication/auth";
import { withRouter } from "react-router";
const Login = ({ submitForm, history }) => {
const [isSubmitted, setIsSubmitted] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
const [login, setLogin] = useState(false);
async function submitForm() {
setIsSubmitted(true);
try {
await fetchLogin(values.email, values.password);
if(login){
auth.login(() => {
history.push("/admin");
});
}
} catch (e) {
auth.login(() => {
history.push("/");
})
}
}
const { handleChange, values, handleSubmit, errors } = useForm(
submitForm,
validate
);
useEffect(() => {
if (localStorage.getItem("user-info")) {
submitForm();
}
}, []);
const fetchLogin = async (email, password) => {
try {
setLoading(true);
const res = await Axios({
method: "POST",
url: `url`,
headers: {
},
data: {
user_email: email,
user_password: password,
},
});
if (res.status === 200) {
setLogin(true);
localStorage.setItem("user-info", JSON.stringify(res.data));
}
setLoading(false);
} catch (err) {
setError(err.message);
setLoading(false);
}
};
return (
<>
<div>
<div className="form-container">
<div className="form-content-left">
<img className="form-img" src={redtruck} alt="spaceship" />
</div>
<div className="form-content-right">
<h1>SIGN IN</h1>
<form className="form" onSubmit={handleSubmit}>
<div className="form-inputs">
<label htmlFor="email" className="form-label">
Email address
</label>
<input
id="signin-email"
type="email"
name="email"
placeholder="Enter email"
className="form-input"
value={values.email}
onChange={handleChange}
/>
{errors.email && <p>{errors.email}</p>}
</div>
<div className="form-inputs">
<label htmlFor="password" className="form-label">
Password
</label>
<input
id="signin-password"
type="password"
name="password"
placeholder="Password"
className="form-input"
value={values.password}
onChange={handleChange}
/>
{errors.password && <p>{errors.password}</p>}
{login ? "" : <p>The password or the email is wrong</p>}
</div>
<button
variant="primary"
type="submit"
className="form-input-btn"
>
LOGIN
</button>
</form>
</div>
</div>
</div>
</>
);
};
export default withRouter(Login);
So the login state is set to true when email and password are right for the user. Later I want to use it when redirecting page to "/admin". But my problem is I have to click twice to login in the first place. Besides I am not sure, if the catch part is right:
catch (e) {
auth.login(() => {
history.push("/");
})
}
So I would be really glad, if you can give me some hint about it.
Thanks...
it is not that you have to press twice, you can check component state, sometimes React batches setState and then update value. You can look at this setState doesn't update the state immediately

Pass multiple variable with POST method in React app

I'm trying to post multiple variables to my Postgres database using a form with React.
This is my current script:
const InputAddress = () => {
const [name, setName] = useState("");
const [problem, setProblem] = useState("");
const [date, setDate] = useState("");
const onSubmitForm = async (e) => {
e.preventDefault();
try {
const body = {
name,
problem,
date,
};
console.log(params);
const response = await fetch("http://localhost:5000/logements", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
console.log(response);
window.location = "/";
} catch (error) {
console.log(error.message);
}
};
return (
<Fragment>
<h1 className="text-center mt-5">Add your address</h1>
<form className="d-flex mt-5" onSubmit={onSubmitForm}>
<label>Name</label>
<input
type="text"
className="form-control"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<label>Comment</label>
<input
type="text"
className="form-control"
value={problem}
onChange={(e) => setProblem(e.target.value)}
/>
<label>Date</label>
<input
type="text"
className="form-control"
value={date}
onChange={(e) => setDate(e.target.value)}
/>
<button className="btn btn-success">Submit</button>
</form>
</Fragment>
);
};
My problem seems to be with the fetch method.
When I submit the form, I get this error message in the console :
bind message supplies 1 parameters, but prepared statement "" requires 3
Is there a simple fix to this problem?

Random Component Behavior

I have 2 components, the problem is that on the first submit click i cant setUser(), (although addUser arguments are giving the correct values) it keeps the original state '', '', but if i click it again it change correctly. I don't know what I'm doing wrong, its my first question sorry if its poorly formatted.
import React, { useState, useEffect } from "react";
import "./notes.css";
import UserNameMailForm from "./userNameMailForm";
const NoteApp = props => {
const [user, setUser] = useState({
userName: "",
email: ""
});
const addUser = (userName, email) => {
const newUser = { userName, email };
setUser(newUser);
console.log(user);
console.log(userName, email);
};
return (
<div className="container p-0">
<div className="screen pt-2">
<p>Users</p>
</div>
<UserNameMailForm addUser={addUser} />
</div>
);
};
export default NoteApp;
The second component is this one:
import React, { useState, useEffect } from "react";
const UserNameMailForm = ({ addUser }) => {
const [userName, setUsername] = useState("");
const [email, setEmail] = useState("");
useEffect(() => {}, []);
const handleSubmit = e => {
e.preventDefault();
addUser(userName, email);
};
return (
<form onSubmit={handleSubmit} className="form-group">
<input
type="text"
className="form-control"
placeholder="User name"
value={userName}
onChange={e => setUsername(e.currentTarget.value)}
/>
<input
type="text"
className="form-control"
placeholder="email"
value={email}
onChange={e => setEmail(e.currentTarget.value)}
/>
<button type="submit" className="btn btn-outline-danger">
Add
</button>
</form>
);
};
export default UserNameMailForm;
You code is working fine, as this example demonstrates:
const { useState } = React;
const NoteApp = props => {
const [user, setUser] = useState({
userName: "",
email: ""
});
const addUser = (userName, email) => {
const newUser = { userName, email };
setUser(newUser);
};
return (
<div className="container p-0">
<div className="screen pt-2">
<p>Users</p>
{JSON.stringify(user)}
</div>
<UserNameMailForm addUser={addUser} />
</div>
);
};
const UserNameMailForm = ({ addUser }) => {
const [userName, setUsername] = useState("");
const [email, setEmail] = useState("");
const handleSubmit = e => {
e.preventDefault();
addUser(userName, email);
};
return (
<form onSubmit={handleSubmit} className="form-group">
<input
type="text"
className="form-control"
placeholder="User name"
value={userName}
onChange={e => setUsername(e.currentTarget.value)}
/>
<input
type="text"
className="form-control"
placeholder="email"
value={email}
onChange={e => setEmail(e.currentTarget.value)}
/>
<button type="submit" className="btn btn-outline-danger">
Add
</button>
</form>
);
};
ReactDOM.render(<NoteApp />, document.getElementById("root"));
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div id="root"></div>
The issue is that setUser is asynchronous, and user is a reference to the previous user object, which will be the object you pass as initial value to useState, so that's why console.log(user); is giving you the previous state.

Resources