REACT/REDUX Action not getting dispatched - javascript

What I am tying to do is when the user clicks on sign in button my action gets dispatch with email and password.
But, my action is not getting dispatched. Like when I checked my redux-dev-tools it is not showing anything:
There are no error message in console. I checked other answer's but nothing helped.
Here is the source code:
LoginScreen.js
import React, { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import ErrorMessage from "../../components/ErrorMessage/ErrorMessage";
import Loader from "../../components/Loader/Loader";
import { login } from "../../redux/actions/userActions";
import "./LoginScreen.scss";
const LoginScreen = ({ location, history }) => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const dispatch = useDispatch();
const userLogin = useSelector((state) => state.userLogin);
const { loading, error, userInfo } = userLogin;
const redirect = location.search ? location.search.split("=")[1] : "/";
useEffect(() => {
if (userInfo) {
history.push(redirect);
}
}, [history, userInfo, redirect]);
const submitHandler = (e) => {
e.preventDefault();
dispatch(login(email, password));
};
return (
<>
<div className="login-container">
<div className="login-form">
<h1>Login</h1>
{loading ? (
<Loader />
) : error ? (
<ErrorMessage error={error} />
) : (
<form onSubmit={submitHandler}>
<div className="login-form-items">
<input
className="login-input"
type="email"
placeholder="Email address"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<input
className="login-input"
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button type="submit" value="submit">
Login
</button>
<h4>OR</h4>
<div className="login-form-social">
<button className="social">
<img
className="googleLogo"
src="/logo/google.svg"
alt="G"
/>{" "}
Login with Google
</button>
<button className="social social-github">
<img
className="githubLogo"
src="/logo/github.svg"
alt="GH"
/>{" "}
Login with GitHub
</button>
</div>
</div>
</form>
)}
</div>
</div>
</>
);
};
export default LoginScreen;
userAction.js
import axios from "axios";
import {
USER_LOGIN_FAIL,
USER_LOGIN_REQUEST,
USER_LOGIN_SUCCESS,
} from "../constants/userConstants";
export const login = () => (email, password) => async (dispatch) => {
try {
dispatch({
type: USER_LOGIN_REQUEST,
});
const config = {
headers: {
"Content-Type": "appllication/json",
},
};
const { data } = await axios.post(
"/api/users/login",
{ email, password },
config
);
dispatch({
type: USER_LOGIN_SUCCESS,
payload: data,
});
localStorage.setItem("userInfo", JSON.stringify(data));
} catch (error) {
dispatch({
type: USER_LOGIN_FAIL,
payload:
error.response && error.response.data.message
? error.response.data.message
: error.message,
});
}
};
userReducer.js
import {
USER_LOGIN_FAIL,
USER_LOGIN_REQUEST,
USER_LOGIN_SUCCESS,
USER_LOGOUT,
} from "../constants/userConstants";
export const userLoginReducer = (state = {}, action) => {
switch (action.type) {
case USER_LOGIN_REQUEST:
return { loading: true };
case USER_LOGIN_SUCCESS:
return { loading: false, userInfo: action.payload };
case USER_LOGIN_FAIL:
return { loading: false, error: action.payload };
case USER_LOGOUT:
return {};
default:
return state;
}
};
store.js
import { createStore, combineReducers, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
// reducers
import { userLoginReducer } from "./reducers/userReducers";
const reducer = combineReducers({
userLogin: userLoginReducer,
});
const userInfoFromStorage = localStorage.getItem("userInfo")
? JSON.parse(localStorage.getItem("userInfo"))
: null;
const initialState = {
userLogin: { userInfo: userInfoFromStorage },
};
const middleware = [thunk];
const store = createStore(
reducer,
initialState,
composeWithDevTools(applyMiddleware(...middleware))
);
export default store;

You've defined your action wrong. With redux-thunk you define your actions like this:
export const login = (email, password) => async (dispatch) => {
// your action code
};
// The above code is equivalent to
export const login = (email, password) => {
return async (dispatch) => {
// your action code
}
}
Not like this:
export const login = () => (email, password) => async (dispatch) => {
// your action code
};
// The above code is equivalent to
export const login = () => {
return (email, password) => {
return async (dispatch) => { // this is wrong
}
}
}
So your action is returning a function which then returns another function.

The way you use it caught my attention. Out of general use. Generally, api operations are done with packages such as saga or thunk. Action is only used as a hyperlink. I suggest you review the article below. I think this build will solve your problem.
https://blog.devgenius.io/reactjs-simple-understanding-redux-with-redux-saga-f635e273e24a

Related

Log-in page not redirecting to user dashboard after firebase log-in

I'm trying to make protected routes for my website using React and firebase. It works fine when users log-in with email but when users log-in with firebase, the page refreshes before it has time to update verification status so it reloads to the log-in page again but when I manually refresh, it goes to the protected page. I'm not sure how to fix so that it will work for firebase log-in as well.
Actions.js:
import * as types from "./actionTypes";
import { auth, googleAuthProvider, facebookAuthProvider } from '../Firebase';
const registerStart = () => ({
type: types.REGISTER_START,
});
const registerSuccess = (user) => ({
type: types.REGISTER_SUCCESS,
payload: user,
});
const registerFail = (error) => ({
type: types.REGISTER_FAIL,
payload: error,
});
const loginStart = () => ({
type: types.LOGIN_START,
});
const loginSuccess = (user) => ({
type: types.LOGIN_SUCCESS,
payload: user,
});
const loginFail = (error) => ({
type: types.LOGIN_FAIL,
payload: error,
});
const logoutStart = () => ({
type: types.LOGOUT_START,
});
const logoutSuccess = (user) => ({
type: types.LOGOUT_SUCCESS,
});
const logoutFail = (error) => ({
type: types.LOGOUT_FAIL,
payload: error,
});
export const setUser = (user) => ({
type: types.SET_USER,
payload: user,
})
const googleSignInStart = () => ({
type: types.GOOGLE_SIGN_IN_START,
});
const googleSignInSuccess = (user) => ({
type: types.GOOGLE_SIGN_IN_SUCCESS,
});
const googleSignInFail = (error) => ({
type: types.GOOGLE_SIGN_IN_FAIL,
payload: error,
});
const fbSignInStart = () => ({
type: types.FACEBOOK_SIGN_IN_START,
});
const fbSignInSuccess = (user) => ({
type: types.FACEBOOK_SIGN_IN_SUCCESS,
});
const fbSignInFail = (error) => ({
type: types.FACEBOOK_SIGN_IN_FAIL,
payload: error,
});
export const registerInitiate = (email, password, displayName) => {
return function (dispatch) {
dispatch(registerStart());
auth.createUserWithEmailAndPassword(email, password).then(({user}) => {
user.updateProfile({
displayName
})
dispatch(registerSuccess(user));
}).catch((error) => dispatch(registerFail(error.message)))
}
};
export const loginInitiate = (email, password) => {
return function (dispatch) {
dispatch(loginStart());
auth.signInWithEmailAndPassword(email, password).then(({user}) => {
dispatch(loginSuccess(user));
}).catch((error) => dispatch(loginFail(error.message)))
}
};
export const logoutInitiate = () => {
return function (dispatch) {
dispatch(logoutStart());
auth.signOut().then((resp) =>
dispatch(logoutSuccess())
).catch((error) => dispatch(logoutFail(error.message)));
}
};
export const googleSignInInitiate = () => {
return function (dispatch) {
dispatch(googleSignInStart());
auth.signInWithPopup(googleAuthProvider).then(({user}) => {
dispatch(googleSignInSuccess(user));
}).catch((error) => dispatch(googleSignInFail(error.message)));
}
};
export const fbSignInInitiate = () => {
return function (dispatch) {
dispatch(fbSignInStart());
auth.signInWithPopup(facebookAuthProvider.addScope("user_birthday, email")).then(({user}) => {
dispatch(fbSignInSuccess(user));
}).catch((error) => dispatch(fbSignInFail(error.message)));
}
};
actionTypes.js:
export const REGISTER_START = "REGISTER_START";
export const REGISTER_SUCCESS = "REGISTER_SUCCESS";
export const REGISTER_FAIL = "REGISTER_FAIL";
export const LOGIN_START = "LOGIN_START";
export const LOGIN_SUCCESS = "LOGIN_SUCCESS";
export const LOGIN_FAIL = "LOGIN_FAIL";
export const LOGOUT_START = "LOGOUT_START";
export const LOGOUT_SUCCESS = "LOGOUT_SUCCESS";
export const LOGOUT_FAIL = "LOGOUT_FAIL";
export const SET_USER = "SET_USER";
export const GOOGLE_SIGN_IN_START = "GOOGLE_SIGN_IN_START";
export const GOOGLE_SIGN_IN_SUCCESS = "GOOGLE_SIGN_IN_SUCCESS";
export const GOOGLE_SIGN_IN_FAIL = "GOOGLE_SIGN_IN_FAIL";
export const FACEBOOK_SIGN_IN_START = "FACEBOOK_SIGN_IN_START";
export const FACEBOOK_SIGN_IN_SUCCESS = "FACEBOOK_SIGN_IN_SUCCESS";
export const FACEBOOK_SIGN_IN_FAIL = "FACEBOOK_SIGN_IN_FAIL";
reducer.js:
const initialState = {
loading: false,
currentUser: null,
error: null,
}
const userReducer = (state = initialState, action) => {
switch(action.type) {
case types.REGISTER_START:
case types.LOGIN_START:
case types.LOGOUT_START:
case types.GOOGLE_SIGN_IN_START:
case types.FACEBOOK_SIGN_IN_START:
return {
...state,
loading: true
};
case types.LOGOUT_SUCCESS:
return {
...state,
currentUser: null,
}
case types.SET_USER:
return {
...state,
loading: false,
currentUser: action.payload,
}
case types.REGISTER_SUCCESS:
case types.LOGIN_SUCCESS:
case types.GOOGLE_SIGN_IN_SUCCESS:
case types.FACEBOOK_SIGN_IN_SUCCESS:
return {
...state,
loading: false,
currentUser: action.payload,
};
case types.REGISTER_FAIL:
case types.LOGIN_FAIL:
case types.LOGOUT_FAIL:
case types.GOOGLE_SIGN_IN_FAIL:
case types.FACEBOOK_SIGN_IN_FAIL:
return {
...state,
loading: false,
error: action.payload,
}
default:
return state;
}
}
export default userReducer;
rootReducer.js:
import userReducer from "./reducer";
const rootReducer = combineReducers({
user: userReducer
})
export default rootReducer;
store.js:
import { createStore, applyMiddleware } from "redux";
import { createLogger } from "redux-logger";
import thunk from "redux-thunk";
import rootReducer from './rootReducer';
const middleware = [thunk];
const logger = createLogger({});
if(process.env.NODE_ENV === "development") {
middleware.push(logger)
}
export const store = createStore(rootReducer, applyMiddleware(...middleware));
login.js:
import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector} from "react-redux";
import { useNavigate, Link } from "react-router-dom";
import { fbSignInInitiate, googleSignInInitiate, loginInitiate } from '../../userauth/actions';
import './login.css';
const Login = () => {
const [state, setState] = useState({
email: "",
password: "",
});
const { email, password } = state;
const { currentUser } = useSelector((state) => state.user);
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
useEffect(() => {
if(currentUser || loading) {
navigate("/dashboard");
}
}, [currentUser, navigate]);
const dispatch = useDispatch();
const handleGoogleSignIn = () => {
dispatch(googleSignInInitiate());
setLoading(true);
};
const handleFBSignIn = () => {
dispatch(fbSignInInitiate());
setLoading(true);
};
const handleSubmit = (e) => {
e.preventDefault();
if(!email || !password) {
return;
}
dispatch(loginInitiate(email, password));
setState({ email: "", password: "" });
setLoading(true);
};
const handleChange = (e) => {
let { name, value } = e.target;
setState({...state, [name]: value });
};
return (
<div>
<div id="logreg-form">
<form className='form-signin' onSubmit={handleSubmit}>
<h1>
Sign in
</h1>
<div className="social-login">
<button
className='btn google-btn social-btn'
type='button'
onClick={handleGoogleSignIn}>
<span>
<i className='fab fa-google-plus-g'>Sign in with Google</i>
</span>
</button>
<button
className='btn facebook-btn social-btn'
type='button'
onClick={handleFBSignIn}>
<span>
<i className='fab fa-facebook-f'>Sign in with Facebook</i>
</span>
</button>
</div>
<p>OR</p>
<input
type="email"
id="inputEmail"
className='form-control'
placeholder='Email Address'
name="email"
onChange={handleChange}
value={email}
required
/>
<input
type="password"
id="inputPassword"
className='form-control'
placeholder='Password'
name="password"
onChange={handleChange}
value={password}
required
/>
<button
className='btn btn-secondary btn-block'
type="submit">
<i className="fas fa-sign-in-alt"></i>Sign In
</button>
<hr />
<p>Don't have an account</p>
<Link to="/signup">
<button
className='btn btn-primary btn-block'
type="button" id="btn-signup">
<i className='fas fa-user-plus'></i>Sign up New Account
</button>
</Link>
</form>
</div>
</div>
)
}
export default Login;
Dashboard.js:
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { logoutInitiate } from '../../userauth/actions';
const Dashboard = () => {
const { currentUser } = useSelector((state) => state.user);
const dispatch = useDispatch();
const handleAuth = () => {
if(currentUser) {
dispatch(logoutInitiate());
}
}
return (
<div>
<h1>User Dashboard</h1>
<br />
<button className='btn btn-danger' onClick={handleAuth}>Logout</button>
</div>
)
}
export default Dashboard
protectedRoute.js:
import React from 'react';
import { useSelector } from 'react-redux';
import LoadingToRedirect from './LoadingToRedirect';
const ProtectedRoute = ({children}) => {
const { currentUser } = useSelector((state) => ({...state.user}));
return currentUser ? children : <LoadingToRedirect />;
}
export default ProtectedRoute;
App.js:
import React, { useEffect, useState } from 'react';
import { Landing, Login, Signup, Contact, Dashboard, Error } from './pages';
import ProtectedRoute from './components/ProtectedRoute';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import { useDispatch } from "react-redux";
import { auth } from "./Firebase";
import { setUser } from './userauth/actions';
import './App.css';
const App = () => {
const dispatch = useDispatch();
useEffect(() => {
auth.onAuthStateChanged((authUser) => {
if(authUser) {
dispatch(setUser(authUser));
} else {
dispatch(setUser(null));
}
})
}, [dispatch]);
return (
<BrowserRouter>
<div className='App'>
<Routes>
<Route exact path="/" element={<Landing/>} />
<Route path="/login" element={<Login/>} />
<Route path="/signup" element={<Signup/>} />
<Route path="/contact" element={<Contact/>} />
<Route
path="/dashboard"
element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
}
/>
<Route path="*" element={<Error />} />
</Routes>
</div>
</BrowserRouter>
)
}
export default App;
If anyone comes across the same situation, I was able to solve this problem on my own and it's a simple fix. The problem was that the user authorization status wasn't updated whenever I called on Protected Routes but instead it just used the initial state when App.js was called. To get the user authorization status, I saved the user auth in my localStorage. Then, whenever I called user auth status in my redirects, I just fetched from my local storage.

React Redux state re-render issues with object from mongodb

These are my codes for creating a new blog post:
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { createBlog, reset } from "../features/blogSlice";
const Createblog = () => {
const dispatch = useDispatch();
const [title, setTitle] = useState("");
const [texts, setTexts] = useState("");
const history = useNavigate();
const { user, isError, isSuccess, message } = useSelector((state) => {
return state.auth;
});
useEffect(() => {
if (!user) {
history("/login");
}
dispatch(reset());
}, [user, isError, isSuccess, message, history, dispatch]);
const handleSubmit = async (e) => {
e.preventDefault();
const data = {
title,
texts,
};
dispatch(createBlog(data));
history("/");
};
return (
<>
<div className="container mt-3">
<div className="row">
<div className="col-3"></div>
<div className="col-6 bg-info">
<h1>Create A New Blog</h1>
</div>
<div className="col-3"></div>
</div>
<div className="row">
<div className="col-3"></div>
<div className="col-6">
<form className="mt-3">
<input
type="text"
name="title"
className="form-control my-2"
placeholder="Type your Title"
onChange={(e) => setTitle(e.target.value)}
/>
<textarea
name="texts"
className="form-control"
id="exampleFormControlTextarea1"
rows="10"
onChange={(e) => setTexts(e.target.value)}
></textarea>
<button className="btn btn-primary col-6 my-2" onClick={handleSubmit}>
Click to post
</button>
</form>
</div>
<div className="col-3"></div>
</div>
</div>
</>
);
};
export default Createblog;
This is my redux slice for creating the Blog
import { createAsyncThunk, createSlice } from "#reduxjs/toolkit";
import blogService from "./blogService";
const initialState = {
blogs: [],
isError: false,
isSuccess: false,
isLoading: false,
message: "",
};
export const createBlog = createAsyncThunk("blogs/createBlog", async (blogData, thunkAPI) => {
try {
const token = thunkAPI.getState().auth.user.token;
return await blogService.createBlog(blogData, token);
} catch (error) {
const message = (error.response && error.response.data && error.response.data.message) || error.message || error.toString();
return thunkAPI.rejectWithValue(message);
}
});
export const getBlogs = createAsyncThunk("blogs/", async (_, thunkAPI) => {
try {
// const token = thunkAPI.getState().auth.user.token;
return await blogService.getBlogs();
} catch (error) {
const message = (error.response && error.response.data && error.response.data.message) || error.message || error.toString();
return thunkAPI.rejectWithValue(message);
}
});
const blogSlice = createSlice({
name: "blogs",
initialState,
reducers: {
reset: (state) => {
return initialState;
},
},
extraReducers: (builder) => {
// Get All Blogs
builder
.addCase(getBlogs.pending, (state) => {
state.isLoading = true;
})
.addCase(getBlogs.fulfilled, (state, action) => {
state.isLoading = false;
state.isSuccess = true;
state.blogs = action.payload;
})
.addCase(getBlogs.rejected, (state, action) => {
state.isLoading = false;
state.isError = true;
state.message = action.payload;
})
// create blog
.addCase(createBlog.pending, (state) => {
state.isLoading = true;
})
.addCase(createBlog.fulfilled, (state, action) => {
state.isLoading = false;
state.isSuccess = true;
state.blogs.push(action.payload);
})
.addCase(createBlog.rejected, (state, action) => {
state.isLoading = false;
state.isError = true;
state.message = action.payload;
});
},
});
export const { reset } = blogSlice.actions;
export default blogSlice.reducer;
And, these are the redux blog service codes:
import Axios from "axios";
const api_Link = "http://localhost:8080/";
const createBlog = async (blogData, token) => {
const config = {
headers: {
Authorization: `Bearer ${token}`,
},
};
const response = await Axios.post(api_Link + `blog`, blogData, config);
return response.data;
};
const getBlogs = async () => {
const response = await Axios.get(api_Link);
const data = response.data.data;
return data;
};
const blogService = {
createBlog,
getBlogs,
};
export default blogService;
And, this is how I view the blog posts:
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { getBlogs, reset } from "../features/blogSlice";
const Blogpage = () => {
const dispatch = useDispatch();
const history = useNavigate();
const { blogs, isSuccess, isLoading, isError, message } = useSelector((state) => state.blogs);
useEffect(() => {
if (isError) {
console.log(message);
}
dispatch(getBlogs());
return () => {
dispatch(reset());
};
}, [history, isError, message, dispatch]);
return (
<>
<div className="container">
<div className="row">
<div className="col">
<h1 className="text-centr">Following are your blogs</h1>
</div>
</div>
{blogs.map((item, sl) => {
return (
<section className="bg-success text-light mt-4" key={sl}>
<div className="row">
<div className="col">
<h1 className="text-start">{item.title}</h1>
<h5 className="text-start bg-success text-light">Author: {item.creator.name}</h5>
<p className="text-start">{item.texts}</p>
</div>
</div>
</section>
);
})}
</div>
</>
);
};
export default Blogpage;
Normally I can view the blog posts. Creating blog, redirecting everything works just fine. The problem occurs only when I try to retrieve anything from the creator field. Please see below. Here is what I get from db
{
_id: new ObjectId("62b7a94583a09428b900a069"),
date: 2022-06-26T00:33:09.838Z,
title: 'This is title',
texts: 'These are texts',
creator: {
_id: new ObjectId("62ae7514d2106b408c190667"),
name: 'Md.Rashel',
email: 'example#gmail.com',
}
Whenever I try to retrieve item.creator.name it shows this error : "Uncaught TypeError: Cannot read properties of undefined (reading 'name')". But, once I reload the page, it works fine again.
I'm not sure how to fix this. I'm not also sure whether it is redux issue or react issue. Could you please help fix the issue? Thanks in advance.

React Context API - dispatch is not a function

Implementing a Log in system with React Context API. When submitted the form with user credentials, getting an error.
Error:
Unhandled Rejection (TypeError): dispatch is not a function
loginCall
src/apiCalls.js:4
1 | import axios from "axios";
2 |
3 | export const loginCall = async (userCredential, dispatch) => {
> 4 | dispatch({ type: "LOGIN_START" });
5 | try {
6 | const res = await axios.post("auth/login", userCredential);
7 | dispatch({ type: "LOGIN_SUCCESS", payload: res.data });
Files:
Login.jsx
import React, { useContext, useRef } from "react";
import bgImg from "../assets/login/tw-bg.png";
import "./styles/login.css";
import TwitterIcon from "#mui/icons-material/Twitter";
import { loginCall } from "../apiCalls";
import {AuthContext} from '../context/AuthContext'
function Login() {
const email = useRef();
const password = useRef();
const context = useContext(AuthContext);
const handleSubmit = (e) => {
e.preventDefault();
loginCall(
{ email: email.current.value, password: password.current.value },
context.dispatch
);
};
console.log(context.user)
return (
<div className="login-container">
<div className="left">
<TwitterIcon className="left-tw-icon" style={{ fontSize: 250 }} />
<img src={bgImg} alt="background" className="login-background" />
</div>
<div className="right">
<TwitterIcon className="right-tw-icon" color="primary" />
<div className="main-title-container">
<span className="main-title-span">Şu anda olup bitenler</span>
</div>
<div className="secondary-title-container">
<span className="secondary-title-span">Twitter'a bugün katıl.</span>
</div>
<div className="form-container">
<form onSubmit={handleSubmit}>
<input type="email" placeholder="Username" ref={email} />
<input type="password" placeholder="Password" ref={password} />
<button type="submit">Log in</button>
</form>
</div>
</div>
</div>
);
}
export default Login;
apiCalls.js
import axios from "axios";
export const loginCall = async (userCredential, dispatch) => {
dispatch({ type: "LOGIN_START" });
try {
const res = await axios.post("auth/login", userCredential);
dispatch({ type: "LOGIN_SUCCESS", payload: res.data });
} catch (error) {
dispatch({ type: "LOGIN_FAILURE", payload: error });
}
};
AuthContext.js
import { Children, createContext, useReducer } from "react";
import AuthReducer from "./AuthReducer";
const INITIAL_STATE = {
user: null,
error: null,
isFetching: false,
};
export const AuthContext = createContext(INITIAL_STATE);
export const AuthContextProvider = ({children}) => {
const [state, dispatch] = useReducer(AuthReducer, INITIAL_STATE);
return (
<AuthContextProvider
value={{
user: state.user,
error: state.error,
isFetching: state.isFetching,
dispatch,
}}
>
{children}
</AuthContextProvider>
);
};
Any help appreciated.
Edit: AuthReducer and AuthActions added.
const AuthReducer = (state, action) => {
switch (action.type) {
case "LOGIN_START":
return {
user: null,
error: null,
isFetching: true,
};
case "LOGIN_FAILURE":
return {
user: null,
error: action.payload,
isFetching: false,
};
case "LOGIN_SUCCESS":
return {
user: action.payload,
error: null,
isFetching: false,
};
}
};
export default AuthReducer
```
export const LOGIN_START = (userCredentials) => {
type:"LOGIN_START"
}
export const LOGIN_SUCCESS = (user) => ({
type:"LOGIN_SUCCESS",
payload:user
})
export const LOGIN_FAILURE = (err) => ({
type:"LOGIN_FAILURE",
})
```
Some comment to handle "mostly code error." It seems all clear to me. But the problem still continues. If there is a point I am missing, it would be great to learn from you.
Thanks in advance.
you can try this:
import axios from "axios";
export const loginCall = (userCredential) => {
return async (dispatch, getState) => {
dispatch(LOGIN_START());
try {
const res = await axios.post("auth/login", userCredential);
dispatch(LOGIN_SUCCESS(res.data);
} catch (error) {
dispatch(LOGIN_FAILURE());
}
};
in your error you see this message:
dispatch is not a function
loginCall
src/apiCalls.js:4
it is quite straight forward. It tells you what the problem is which dispatch. it is loginCall and and loginCall is in apiCalls. try to focus on the error that you see.
dispatch basically fires the function that you want to call. In your syntax, you put an object in the dispatch({some stuff}), but it actually expects you to call a function there.
I am not sure if my solution will fix everything but in the worst case, you should at least get a different error. :)
I had the same problem recently working on a similar project.
npm install cors
then in your index.js file with your express declarations,
const cors = require('cors'),
then at the very top your code but below your imports,
app.use(cors())
That will probably fix it.

redux: action is fired but not changing state

I have a problem with my code.
when I dispatch an action Of type "LOGIN"
The next component is Called with this HOC
withHOC
import React from "react";
import { connect } from "react-redux";
export default function withState(WrappedComponent) {
async function mapStateToProps(reduxState) {
const state = await reduxState.initialReducer;
return {
...state ,
};
}
return connect(
mapStateToProps,
null
)(function (props) {
return (
<React.Fragment>
<WrappedComponent {...props} />
</React.Fragment>
);
});
}
DispatchFile.js
const SignIn = props => {
const classes = useStyles();
function handleClick(){
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
props.dispatch({
type: LOGIN,
cred: {email, password}
})
}
return(
<div className={classes.inputGroup}>
<TextField type="email" className={classes.btnColor} id="email" label="E-mail" variant="filled" />
<TextField type="password" className={classes.btnColor} id="password" label="Password" variant="filled" />
<Button className={classes.submit} onClick={handleClick}> Login </Button>
</div>
)
}
the action is dispatched successfully to my rootReducer
Root Reducer File
import { combineReducers} from 'redux';
import initialReducer from "./initialReducer";
const rootReducer = combineReducers({
initialReducer,
});
export default rootReducer;
initialReducer
import { CREATE_NEW_USER, LOGIN, REMOVE_USER } from "../actions";
import API from "../actions/API";
let initialState = {
id:"",
username:"",
profileImageUrl:"",
token:"",
isLogged:false,
}
export default async function initialReducer(state = initialState, action){
let newState = {...state};
switch(action.type){
case LOGIN:
const res = await API.login(action.cred);
if( res.code === 200){
console.log(res)
if(action.cred.keepMeLogged)await localStorage.setItem("user", res.res)
const { id, username, profileImageUrl, token} = res.res;
return {
...newState,
id,
username,
profileImageUrl,
token,
isLogged: true,
}
}
else{
return res
}
default:
if(localStorage.getItem("user")){
initialState = localStorage.getItem("user");
}
return newState;
}
}
The action is called successfully and the API returns the correct values
now when I check my redux dev tool the state is set with an empty state {}
what I tried:
searched for similar questions and tried fiddling with code but still, the redux state won't change

Actions must be plain objects. Trying to dispatch an actions into a redux-form

I'm trying to execute an async function when a form is submitted with redux-form, but no matter what, the error:
Actions must be plain objects. Use custom middleware for async actions.
Is always fired... here is my config:
createStore:
export const store = createStore(
rootReducer,
compose(
applyMiddleware(thunk),
window.devToolsExtension ? window.devToolsExtension() : f => f
)
);
The actions with thunk:
const loginUser = userData => {
return {
type: fb_actions.LOGIN,
payload: userData
}
};
export const loginFirebase = (email, password) => {
firebase.auth()
.signInWithEmailAndPassword(email, password)
.then(authData => {
return dispatch => {
dispatch(loginUser({email: email, password: password}))
}
})
};
The component:
import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import logo from '../static/logo-horizontal-black.svg';
import '../styles/Login.scss';
import renderLoginField from '../helpers/renderLoginField';
class Login extends Component {
constructor() {
super();
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onFormSubmit(fields) {
const { login } = this.props;
login(fields.email, fields.password);
};
render() {
const {handleSubmit} = this.props;
return (
<div className='row'>
<div className='col-xs-12 col-sm-6 col-md-4 col-md-offset-4 col-md-offset-3'>
<section className='panel panel-default panel-login'>
<div className='panel-heading'>
<img src={logo} role='presentation' alt='cc-logo' className='img-responsive cc-logo' />
</div>
<div className='panel-body'>
<form onSubmit={handleSubmit(this.onFormSubmit)}>
<Field icon='mail' type='email' component={renderLoginField} name='email' />
<Field icon='password' type='password' component={renderLoginField} name='password' />
<button type='submit' className='btn btn-primary login-btn'>Login</button>
</form>
</div>
</section>
</div>
</div>
);
}
};
Login = reduxForm({ form: 'loginForm' })(Login);
export default Login;
And the container:
import { connect } from 'react-redux';
import Login from '../components/Login';
import { loginFirebase } from '../actions/firebaseActions';
const mapStateToProps = (state, ownProps) => {
return {
authData: state.auth
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
login: (email, password) => dispatch(loginFirebase(email, password))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Login);
Any idea about this?
I guess the action has to be chained as below,
export const loginFirebase = (email, password) => dispatch =>
firebase.auth()
.signInWithEmailAndPassword(email, password)
.then( authData => dispatch(loginUser({ email: email, password: password})));

Categories

Resources