_this2.props.signup is not a function in React Redux app - javascript

Please note that I've already checked answers in this question and nothing seems to work.
I'm using this repo as a boilerplate. Instead of firebase database, I'm trying to send username and email with the firebase auth userid , to the node server. I created an action creator signup to handle this.
This is signup.js action creator
import * as types from '../constants/action_types';
import axios from 'axios';
export const signup = (user) => {
console.log(user);
return async dispatch => {
try {
const response = await axios.get('http://localhost:5000/api/user/register', user)
const data = await {response};
dispatch({
type : types.SIGN_UP,
payload : data.fromback
})
} catch (error) {
console.lot(error)
}
}
}
Then I've connected it with the component with mapDispatchToProps., So,under the SignUpPage component, React dev tools shows signup as a function. But when it get triggers, it gives an error saying _this2.props.signup is not a function Why's that ?
This is my SignUpPage component
import React, { Component } from 'react';
import {
Link,
withRouter,
} from 'react-router-dom';
import { auth } from '../../firebase';
import * as routes from '../../constants/routes';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import {signup} from './../../actions/signup';
const SignUpPage = ({ history }) =>
<div>
<h1>SignUp</h1>
<SignUpForm history={history} />
</div>
const updateByPropertyName = (propertyName, value) => () => ({
[propertyName]: value,
});
const INITIAL_STATE = {
username: '',
email: '',
passwordOne: '',
passwordTwo: '',
error: null,
};
class SignUpForm extends Component {
constructor(props) {
super(props);
this.state = { ...INITIAL_STATE };
}
onSubmit = (event) => {
const {
username,
email,
passwordOne,
} = this.state;
const {
history,
} = this.props;
auth.doCreateUserWithEmailAndPassword(email, passwordOne)
.then(authUser => {
const userid = authUser.user.uid;
const user = { email, userid };
this.props.signup(user);
})
.catch(error => {
this.setState(updateByPropertyName('error', error));
});
event.preventDefault();
}
render() {
const {
username,
email,
passwordOne,
passwordTwo,
error,
} = this.state;
const isInvalid =
passwordOne !== passwordTwo ||
passwordOne === '' ||
username === '' ||
email === '';
return (
<form onSubmit={this.onSubmit}>
<input
value={username}
onChange={event => this.setState(updateByPropertyName('username', event.target.value))}
type="text"
placeholder="Full Name"
/>
<input
value={email}
onChange={event => this.setState(updateByPropertyName('email', event.target.value))}
type="text"
placeholder="Email Address"
/>
<input
value={passwordOne}
onChange={event => this.setState(updateByPropertyName('passwordOne', event.target.value))}
type="password"
placeholder="Password"
/>
<input
value={passwordTwo}
onChange={event => this.setState(updateByPropertyName('passwordTwo', event.target.value))}
type="password"
placeholder="Confirm Password"
/>
<button disabled={isInvalid} type="submit">
Sign Up
</button>
{ error && <p>{error.message}</p> }
</form>
);
}
}
const SignUpLink = () =>
<p>
Don't have an account?
{' '}
<Link to={routes.SIGN_UP}>Sign Up</Link>
</p>
const mapDispatchToProps = dispatch => bindActionCreators({ signup }, dispatch)
export default connect(null, mapDispatchToProps)(withRouter(SignUpPage));
export {
SignUpForm,
SignUpLink,
};

Its not a prop,
you've imported it as a function,
you can directly use it as function like this
import {signup} from './../../actions/signup';
.....
auth.doCreateUserWithEmailAndPassword(email, passwordOne)
.then(authUser => {
const userid = authUser.user.uid;
const user = { email, userid };
signup(user);
})
.catch(error => {
this.setState(updateByPropertyName('error', error));
});

Related

reactjs and firebase data is not uploaded even though the code has no errors, might be due to overlaping of two .js files

So this is a really weird one, im trying to build a instagram clone and i two files called signup.js and formikpostup.js when i try to create sub collection "posts in my collection "users" it dosent work. BUT when i uploaded data from formikpostup.js in to another collection called "realusers" it worked (it created a sub collection) but i had not added signup.js data in "realusers" when i did add it the formikpostup.js stopped working. This is the code for Signup.js:
import React from "react";
import "./signup.css";
import insta from "./svg/insta.svg";
import { Formik } from "formik";
import * as Yup from "yup";
import validator from "validator";
import { auth, db } from "../../firebase";
import {
createUserWithEmailAndPassword,
getAuth,
onAuthStateChanged,
setCurrentLoggedInUser
} from "firebase/auth";
import {
collection,
addDoc,
set,
doc,
docs,
setDoc,
query,
where,
limit,
onSnapshot
} from "firebase/firestore";
export default class SignUp extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
/*getUsername = () => {
const authp= getAuth();
onAuthStateChanged(auth, (user) => {
if (user) {
}
});
};
componentDidMount(){
const use= doc(db,"users","posts");
console.log(use)
}
*/
render() {
const signupSchema = Yup.object().shape({
email: Yup.string().email().required("An email is required"),
username: Yup.string().required().min(2, "A username is required"),
password: Yup.string()
.required()
.min(6, "Your password should have atleast 6 characters")
});
const setUser = (e) => {
this.props.user(e);
console.log(this.props.user);
};
const authz = getAuth();
var emailcheck = () => {};
var passcheck = () => {};
var usercheck = () => {};
const onSignUp = async (email, password, username) => {
try {
const authUser = await createUserWithEmailAndPassword(
auth,
email,
password
);
/*db.collection("users")
.doc(authUser.user.email)({ Yar whatsapp pe hi
owner_uid: authUser.user.uid,
username: username,
email: authUser.user.email
})
.then(() => {
console.log("CREATED");
})
.catch((e) => {
alert("Bruh");
});*/
try {
const docRef = await addDoc(collection(db, "realusers"), {
owner_uid: authUser.user.uid,
username: username,
email: authUser.user.email,
profile_pic: await randomProfiles()
});
console.log("CREATED");
this.props.phase(0);
setUser(username);
} catch (e) {
console.log(e);
}
} catch (error) {
console.log(error);
}
};
const randomProfiles = async () => {
const respone = await fetch("https://randomuser.me/api");
const data = await respone.json();
return data.results[0].picture.large;
};
return (
<div className="container">
<div className="signin-insta">
<img
alt=""
src={insta}
className="signin-inst"
width="150px"
height="130px"
/>
</div>
<div className="credit">𝐀 𝐂𝐥𝐨𝐧𝐞 𝐁𝐲 𝐌𝐨𝐞𝐞𝐳 𝐑𝐚𝐦𝐚𝐲</div>
{
((emailcheck = (e) => {
if (validator.isEmail(e) === false && e.length >= 1) {
return (
<div className="email-error">
Please Enter Valid Email Address
</div>
);
}
}),
(usercheck = (user) => {
if ((user.length <= 4 || user.length >= 13) && user.length !== 0) {
return (
<div className="email-error">
Username can be of 5 to 12 characters only
</div>
);
}
}),
(passcheck = (pass) => {
if (pass.length <= 5 && pass.length >= 1) {
return (
<div className="email-error">Please Enter Valid Password</div>
);
}
}))
}
{/*--------------------------------------------------------------*/}
<Formik
initialValues={{
email: "",
username: "",
password: ""
}}
onSubmit={(values) => {
onSignUp(values.email, values.password, values.username);
}}
validationSchema={signupSchema}
validateOnMount={true}
>
{({ handleChange, handleBlur, handleSubmit, values, isValid }) => {
return (
<div>
<div className="input-sign">
<input
className="sign-in-input"
placeholder="Email Address"
type="email"
onChange={handleChange("email")}
onBlur={handleBlur("email")}
value={values.email}
/>
{emailcheck(values.email)}
<input
className="sign-in-input"
placeholder="Username"
onChange={handleChange("username")}
onBlur={handleBlur("username")}
value={values.username}
/>
{usercheck(values.username)}
<input
className="sign-in-input"
type="password"
placeholder="Password"
onChange={handleChange("password")}
onBlur={handleBlur("password")}
value={values.password}
/>
{passcheck(values.password)}
</div>
<div className="forgot-pass">Forgot Password?</div>
<div className="signin-Button">
<button className="signin-Button fa" onClick={handleSubmit}>
Sign Up
</button>
</div>
<div className="already fb">
Dont have an account?{" "}
<span
className="already-signin"
onClick={() => {
this.props.phase(-1);
}}
>
LogIn
</span>
</div>
</div>
);
}}
</Formik>
{/*--------------------------------------------------------------*/}
</div>
);
}
}
code for fomikpostup.js:
import React from "react";
import "./formikpostup.css";
import { Formik } from "formik";
import * as Yup from "yup";
import Divider from "../homepage/divider";
import validUrl from "valid-url";
import { auth, db } from "../../firebase";
import {
collection,
addDoc,
set,
doc,
docs,
setDoc,
query,
where,
limit,
onSnapshot,
serverTimestamp
} from "firebase/firestore";
export default class FormikPostupload extends React.Component {
constructor(props) {
super(props);
this.state = {
thumbnail:
"https://getstamped.co.uk/wp-
content/uploads/WebsiteAssets/Placeholder.jpg",
loggedUser: null
};
}
changePhase = (x) => {
console.log(this.props.phase(x));
};
changeUser = (x) => {
console.log(this.props.user(x));
};
render() {
const uploadPostScheme = Yup.object().shape({
imageUrl: Yup.string().url().required("A url is required"),
caption: Yup.string().max(
200,
"Caption has reached the maximum character limit"
)
});
const uploadPostOnline = (imageUrl, caption) => {
const userId = auth.currentUser.uid;
console.log(userId);
const collectionRef = collection(db, "realusers", userId, "posts");
addDoc(collectionRef, {
imageUrl,
caption,
likes: 1,
likesByUsers: [],
comments: [],
createdAt: serverTimestamp()
});
};
const formikPostUploader = (navigator) => {
const thumbnailUrl = this.state.thumbnail;
const loggedUser = this.state.loggedUser;
};
const placeholderimg =
"https://getstamped.co.uk/wp-
content/uploads/WebsiteAssets/Placeholder.jpg";
const urllistner = (e) => {
this.setState({ thumbnail: e.nativeEvent.srcElement.value });
};
var sharelistner = (e) => {
if (e) {
this.props.phase(0);
}
};
return (
<Formik
initialValues={{ caption: "", imageUrl: "" }}
onSubmit={(values) => uploadPostOnline(values.imageUrl, values.caption)}
validationSchema={uploadPostScheme}
>
{({
handleBlur,
handleChange,
handleSubmit,
values,
errors,
isValid,
setFieldValue
}) => {
return (
<div>
<div className="cont">
<div>
<img
id="image"
alt=""
src={
this.state.thumbnail
? this.state.thumbnail
: placeholderimg
}
width="100px"
height="100px"
/>
<textarea
placeholder="Write A Caption"
className="input-caption"
onChange={handleChange("caption")}
onBlur={handleBlur("caption")}
value={values.caption}
></textarea>
</div>
<div className="new-post-bottom">
<Divider />
{/*----------------------------------------------------------------*/}
<input
className="input-image"
placeholder="Enter Image Url"
onChange={(e) => {
handleChange("imageUrl")(e);
urllistner(e);
}}
onBlur={handleBlur("imageUrl")}
value={values.imageUrl}
/>
{/*----------------------------------------------------------------*/}
{errors.imageUrl && (
<div className="image-url-error">{errors.imageUrl}</div>
)}
</div>
</div>
{
(sharelistner = (e) => {
this.props.phase(0);
})
}
<button
type="submit"
className="share-button-newpost"
onClick={(e) => {
handleSubmit();
sharelistner(e);
}}
disabled={!isValid}
>
Share
</button>
</div>
);
}}
</Formik>
);
}
componentDidMount() {
document.getElementById("image").addEventListener("error", (e) => {
e.target.src =
"https://getstamped.co.uk/wp-content/uploads/WebsiteAssets/Placeholder.jpg";
});
}
}
There is no modification in firebase rules here is the code for rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if
request.time < timestamp.date(2022, 10, 30);
}
}
}

Uncaught TypeError: react__WEBPACK_IMPORTED_MODULE_0__.useContext(...) is null when calling set function

I'm trying to set up a user login system using the userContext and localSotrage of the browser.
I have a first file that includes my provider and my context:
Auth.jsx
import { hasAuthenticated } from '../services/AuthAPI';
export const AuthContext = createContext()
const AuthProvider = ({children}) => {
const [auth, setAuth] = useState(hasAuthenticated());
const value = useMemo(() => ({auth, setAuth}, [auth, setAuth]));
return (
<AuthContext.Provider value={value}>{children}</AuthContext.Provider>
)
}
export default AuthProvider
export const AuthState = () => {
return useContext(AuthContext)
}
I also have a page that allows to manage elements of the LocalStorage and to know if a user is already connected (it for now hardcoded):
AuthAPI.jsx
export function hasAuthenticated() {
const token = getItem('sessionToken');
const result = token ? tokenIsValid(token) : false;
if (false === result) {
removeItem('sessionToken');
}
return result;
}
export function login(credentials) {
addItem('sessionToken', 'tokenSample');
return true;
};
export function logout() {
removeItem('sessionToken');
}
function tokenIsValid(token) {
// const { exp: expiration } = jwtDecode(token);
// if (expiration * 1000 > new Date().getTime()) {
// return true;
// }
return true;
}
And finally I have my connection page which must update the auth variable using the context:
Login.jsx
import { useNavigate } from 'react-router-dom';
import { AuthContext } from '../contexts/Auth';
import { login } from '../services/AuthAPI';
const Login = () => {
const navigate = useNavigate();
const {auth, setAuth} = useContext(AuthContext);
const [user, setUser] = useState({
username: "",
password: ""
})
const handleChange = ({ currentTarget }) => {
const { name, value } = currentTarget;
setUser({ ...user, [name]: value })
}
async function handleSubmit(event) {
event.preventDefault();
try {
const response = await login(user);
setAuth(response);
navigate('news', { replace: true });
console.log('oui');
} catch (e) {
console.error(e);
}
}
useEffect(() => {
if (auth) {
navigate('news', { replace: true });
}
}, [navigate, auth]);
return (
<div className="container border rounder mt-5 p-3 bg-light">
<form className="form-profile" onSubmit={setAuth(true)} >
<fieldset>
<legend>Se connecter</legend>
<div className="form-group">
<label htmlFor="email">Email</label>
<input
type="text"
name="username"
className="form-control"
id="email"
placeholder="mail#mail.fr"
onChange={handleChange}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
name="password"
className="form-control"
id="password"
placeholder="Password"
onChange={handleChange}
/>
</div>
<button type="submit" className="btn btn-outline-primary">
Se connecter
</button>
</fieldset>
</form>
</div>
);
};
export default Login;
But React returns this error:
Uncaught TypeError: react__WEBPACK_IMPORTED_MODULE_0__.useContext(...) is null site:stackoverflow.com at line setAuth(response); from Login.jsx
Do you have any idea ?

How to update state with redux

I'm trying to build simple login form (data for authorization from API). So I have Slice for auth here is code :
auth.js
import { createSlice } from '#reduxjs/toolkit'
export const authSlice = createSlice({
name: 'auth',
initialState: {
isLoggedIn: false,
token: null,
role: null
},
reducers: {
logIn: (state) => {
state.isLoggedIn = true
},
role:(state, action) =>{
state.role = action.payload
},
token:(state, action) =>{
state.token = action.payload
},
logOut: (state) => {
state.isLoggedIn = false
},
},
})
export default authSlice.reducer;
export const { logIn, logOut, role, token } = authSlice.actions
authService.js :
import axios from 'axios';
import { api } from '../api/index'
export function authenticateUser(username, password) {
axios
.post(api + 'login', {username, password})
.then(res => {
console.log(res.headers.authorization)
})
}
LoginForm.js
import React, { Component } from 'react';
import { Form, Col, Button } from 'react-bootstrap';
import { IoMdLogIn } from "react-icons/all";
import { authenticateUser } from '../services/authService'
export default class LoginForm extends Component{
constructor(props) {
super(props);
this.state = this.initialState;
this.credentialsChange = this.credentialsChange.bind(this);
this.userLogin= this.userLogin.bind(this);
}
initialState = {
username: '', password: ''
}
userLogin = (e) => {
e.preventDefault();
authenticateUser(this.state.username, this.state.password);
this.setState( () => this.initialState)
}
credentialsChange = e => {
this.setState({
[e.target.name]:e.target.value
});
}
render(){
const {username, password} = this.state;
return(
<Form onSubmit={this.userLogin} id="loginFormId">
<Form.Row>
<Form.Group as={Col} controlId="formGridCountry">
<Form.Label>Username</Form.Label>
<Form.Control required autoComplete="off"
type="text" name="username"
value={username}
onChange={this.credentialsChange}
className={"bg-light"}
placeholder="Username" />
</Form.Group>
</Form.Row>
<Form.Row>
<Form.Group as={Col} controlId="formGridZipCode">
<Form.Label>Password</Form.Label>
<Form.Control required autoComplete="off"
type="password" name="password"
value={password}
onChange={this.credentialsChange}
className={"bg-light"}
placeholder="Password" />
</Form.Group>
</Form.Row>
<Button type="submit" variant="success">
<IoMdLogIn />
</Button>
</Form>
);
}
}
What I'm trying to reach is : I want to update state isLoggedIn : true after calling function authenticateUser.
I've tried to use const dispatch = useDispatch() and then calling dispatch(logIn()) but it's throwing error.
Where should I call dispatcher to update state?
You need to call the dispatcher in your AuthService.js in the api response.
Check the response, if it is ok, store it. If your redux is well implemented, it will work.
axios
.post(api + 'login', {username, password})
.then(res => {
console.log(res.headers.authorization)
//Call it here, or create a function and call it here.
})
}
If it doesn't work, please share the error with us

React Context API does not update after calling dispatch

I have a login component that stores the user information in the global state after a successful login. The login component is pretty straight forward. It contains a form with a handleSubmit event that calls an endpoint. Based on the result of that endpoint an action is taken. The login component looks like this.
import React, { Component } from 'react';
import { StateContext } from '../state';
import { login } from '../repositories/authenticationRepository';
class Login extends Component {
static contextType = StateContext;
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
message: '',
};
}
handleChange = (event) => {
const { name, value } = event.target;
this.setState({ [name]: value });
}
handleSubmit = async (event) => {
event.preventDefault();
const [{}, dispatch] = this.context;
const { history } = this.props;
const { email, password } = this.state;
const isLoggedInResponse = await login({ email, password });
if (isLoggedInResponse.data.type === 'error') {
this.setState({ message: isLoggedInResponse.data.message });
return;
}
dispatch({ type: 'storeUserInformation', userInformation: isLoggedInResponse.data.message });
history.push('/');
}
render() {
const { email, password, message } = this.state;
return (
<div className="login-wrapper">
<form onSubmit={this.handleSubmit}>
<label htmlFor="email">
Email:
<input autoComplete="off" name="email" type="text" value={email} onChange={this.handleChange} />
</label>
<label htmlFor="password">
Password:
<input autoComplete="off" id="password" name="password" type="password" value={password} onChange={this.handleChange} />
</label>
{message.length > 0 && <span className="text-danger error">{message}</span> }
<input className="btn btn-secondary" type="submit" value="Submit" />
</form>
</div>
);
}
}
export default Login;
When testing it myself I can see the user information being set in the ReactJS devtools. Of course I want to test this automatically using a unit test, so I wrote the following.
jest.mock('../../repositories/authenticationRepository');
import React from 'react';
import { mount } from 'enzyme';
import Login from '../../pages/Login';
import { StateProvider } from '../../state';
import { login } from '../../repositories/authenticationRepository';
import { act } from 'react-dom/test-utils';
import history from '../../sitehistory';
import { BrowserRouter as Router } from 'react-router-dom';
import { reducer } from '../../reducer';
it('Saves the user information in the store on a succesfull login', async () => {
login.mockReturnValue(({ data: { type: 'success', message: 'Message should be stored' }}));
let initialStateMock = {}
const wrapper = mount(
<StateProvider initialState={initialStateMock} reducer={reducer}>
<Router>
<Login history={history} />
</Router>
</StateProvider>
);
let emailEvent = { target: { name: 'email', value: 'test#example.com'} }
let passwordEvent = { target: { name: 'password', value: 'password'} }
wrapper.find('input').first().simulate('change', emailEvent);
wrapper.find('input').at(1).simulate('change', passwordEvent);
const submitEvent = { preventDefault: jest.fn() }
await act(async () => {
wrapper.find('form').first().simulate('submit', submitEvent);
});
act(() => {
wrapper.update();
});
console.log(initialStateMock); // expected { userInformation: 'Message should be stored' } but got {}
});
I expect the initialStatemock to have the value of { userInformation: 'Message should be stored' }. However it still has the initial value of {}. I tried wrapper.update() to force a refresh but to no avail. What am I overlooking?

How to successfully register users within redux using firebase auth

I keep getting the error undefined when registering a user.
I'm not sure if react is obtaining the states information correctly. Maybe it could be the onChange value, or maybe im missing something else.
I referenced this
How to implement Firebase authentication with React Redux?
but still unsure, what the error can be.
It shows that the user has been sign up on the backend like this.
Demo
https://stackblitz.com/edit/react-h9ekc4
Actions
export const onEmailSignUpChangeAction = value => ({
type: EMAIL_SIGN_UP_CHANGE,
email: value
})
export const onPasswordSignUpChangeAction = value => ({
type: PASSWORD_SIGN_UP_CHANGE,
password: value
})
export const onEmptySignUpEmailClick = () => ({
type: 'EMPTY_SIGN_UP_EMAIL'
})
export const onEmptySignUpPasswordClick = () => ({
type: 'EMPTY_SIGN_UP_PASSWORD'
})
export const signUp = () => (dispatch, getState) => {
const {signUpAuth} = getState();
if (signUpAuth.emailSignUp === '') {
dispatch(onEmptySignUpEmailClick())
}
if (signUpAuth.passwordSignUp === '') {
dispatch(onEmptySignUpPasswordClick())
}
else {
firebaseAuth.createUserWithEmailAndPassword(signUpAuth.emailSignUp, signUpAuth.passwordSignUp)
.then(() => console.log('signUpok'))
.catch( function (error) {
let errorCode = error.code;
let errorMessage = error.message;
alert(errorMessage)
});
}
}
SignUp.js
import React, { Component } from 'react';
import { withRouter } from "react-router-dom";
import { connect } from "react-redux";
import { signUp, onEmailSignUpChangeAction, onPasswordSignUpChangeAction } from '../actions/';
class SignUp extends Component {
state = {
email: "",
password: ""
}
// onChange = (e) =>{
// this.setState({
// [e.target.name] : e.target.value
// })
// }
handleSubmit = (e) => {
e.preventDefault();
const register = this.props.signUp();
console.log(register);
(register === true) && this.props.history.push('/');
console.log(this.state)
}
render() {
return (
<div className="container">
<div className="row">
<div className="col-md-6">
<h1>Sign Up</h1>
<form onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="exampleInputEmail1">Email address</label>
<input
type="email"
className="form-control"
id="email"
onChange={this.props.onEmailSignUpChangeAction}
aria-describedby="emailHelp"
value={this.props.emailSignUp}
placeholder="Enter email" />
<small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div className="form-group">
<label htmlFor="exampleInputPassword1">Password</label>
<input
type="password"
className="form-control"
id="password"
value={this.props.passwordSignUp}
onChange={this.props.onPasswordSignUpChangeAction}
placeholder="Password" />
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (state) => ({
user: state.auth.user,
emailSignUp: state.signUpAuth.emailSignUp,
passwordSignUp: state.signUpAuth.passwordSignUp
})
const mapDispatchToProps = (dispatch) => ({
signUp: () => dispatch(signUp()),
onEmailSignUpChangeAction: (event) => dispatch(onEmailSignUpChangeAction(event.target.value)),
onPasswordSignUpChangeAction: (event) => dispatch(onPasswordSignUpChangeAction(event.target.value)),
});
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(SignUp));
Reducers.js
const initialState = {
emailSignUp: '',
passwordSignUp: '',
errorTextEmailSignUp: '',
errorTextPasswordSignUp: ''
}
export default (state = initialState, action) => {
switch (action.type) {
case EMAIL_SIGN_UP_CHANGE:
return {
...state,
emailSignUp: action.email
}
case PASSWORD_SIGN_UP_CHANGE:
return {
...state,
passwordSignUp: action.password
}
case EMPTY_SIGN_UP_EMAIL:
return {
...state,
errorTextEmailSignUp: 'This field is required'
}
case EMPTY_SIGN_UP_PASSWORD:
return {
...state,
errorTextPasswordSignUp: 'This field is required'
}
default:
return state
}
}
If you want to pass this.props.emailSignUp and this.props.passwordSignUp into your signUp function you could try:
export const signUp = (email, password) => { return (dispatch) => {
if (email === '') {
dispatch({ type: EMPTY_SIGN_UP_EMAIL })
}
else if (password === '') {
dispatch({ type: EMPTY_SIGN_UP_PASSWORD })
}
else {
firebaseAuth.createUserWithEmailAndPassword(email, password)
.then(() => console.log('signUpok'))
.catch( function (error) {
let errorCode = error.code;
let errorMessage = error.message;
alert(errorMessage)
});
}
}
}
Then call your function this.props.signUp(this.props.emailSignUp, this.props.passwordSignUp)
You are assigning signUp method's return to subscribed variable but that method does return nothing.
Since its execution is asynchronous, you may need to dispatch an action that will cause a reducer to store the created user in the state when creation has succeeded, then make use of a selector for retrieving that user for instance.

Categories

Resources