Reputation: 57
User is always udefined. React + Redux. This is my first day using Redux. This is my reducer.
const initialState = {
user: 'User'
}
export function auth(state = initialState, action: any) {
const {type, payload} = action;
switch (type) {
case "REGISTER_SUCCESS":
return {
...state,
user: payload.user,
};
case "REGISTER_FAIL":
return {
...state,
user: null,
};
case "LOGIN_SUCCESS":
return {
...state,
user: payload.user,
};
case "LOGIN_FAIL":
return {
...state,
user: null,
};
case "LOGOUT":
return {
...state,
user: null,
};
default:
return state;
}
}
console.log always return "User {user: undefined, dispatch: ƒ}". Although he seems to have to output something anyway. This is my Sign In component.
import React, {SyntheticEvent, useState} from 'react';
import {Password} from "../../../ui/input/password/password";
import {Button} from "../../../ui/button/button";
import {Input} from '../../../ui/input/input';
import {Text} from "../../../ui/text/text";
import {NavLink} from "react-router-dom";
import {connect} from "react-redux";
import {login as onHandleLogin} from "../../../core/redux/actions/auth";
import {useDispatch} from "react-redux";
function SignInForm(props: any) {
const [login, setLogin] = useState<string>("")
const [password, setPassword] = useState<string>("")
const dispatch = useDispatch()
function onHandleSubmit(e: SyntheticEvent) {
e.preventDefault()
dispatch(onHandleLogin(login, password))
}
function onHandleCheck() {
return !(login && password)
}
console.log('User', props)
return (
<>
<form onSubmit={onHandleSubmit}>
<h1>Sign In</h1>
<Input setValue={setLogin} value={login} label="Login"/>
<Password
label="Password"
setValue={setPassword}
value={password}
/>
<Button disabled={onHandleCheck()} text="Sign In"/>
<Text>Not a member yet? <NavLink to="/register">Sign up</NavLink></Text>
</form>
<span>User: {props.user}</span>
</>
);
}
const mapStateToProps = (state: { user: any; }) => {
return {
user: state.user
};
}
export default connect(mapStateToProps)(SignInForm)
As I said, this is my first encounter with Redux. I will be glad for any help. TY)
EDIT
roodReducer:
import {combineReducers} from "redux";
import {auth} from "./reducers/auth";
export default combineReducers({
auth,
})
Upvotes: 0
Views: 50
Reputation: 1146
The following code is a small implementation of your scenario. The code uses connect HOC to fetch data from redux.
Note: The commented code is the one that uses useSelector. Feel free to use the either of the two Please refer to the code: https://stackblitz.com/edit/react-8ivxam
Upvotes: 1