I am having tough time updating blog post via React Redux Axio. My server is an Express JS server with Mongodb as database.
This is my post slice:
import { createAsyncThunk, createSlice } from "#reduxjs/toolkit";
import blogService from "./blogService";
const initialState = {
allposts: [],
isError: false,
isSuccess: false,
isLoading: false,
message: "",
};
export const getAllPosts = createAsyncThunk("allposts", async (post) => {
try {
return await blogService.getAllPosts(post);
} catch (error) {
console.log("Error here");
return error;
}
});
export const updatePost = createAsyncThunk("update", async (id, { title, body }) => {
try {
return await blogService.editPost(id, { title, body });
} catch (error) {
console.log("Error here");
return error;
}
});
const postSlice = createSlice({
name: "allposts",
initialState,
reducers: {
reset: (state) => {
return initialState;
},
},
extraReducers: (builder) => {
// Get All Blogs
builder
.addCase(getAllPosts.pending, (state) => {
state.isLoading = true;
})
.addCase(getAllPosts.fulfilled, (state, action) => {
state.isLoading = false;
state.isSuccess = true;
state.allposts = action.payload;
})
.addCase(getAllPosts.rejected, (state, action) => {
state.isLoading = false;
state.isError = true;
state.message = action.payload;
})
// Edit blog post
.addCase(updatePost.pending, (state) => {
state.isLoading = true;
})
.addCase(updatePost.fulfilled, (state, action) => {
state.isLoading = false;
state.isSuccess = true;
console.log(action.payload);
state.map((post) => {
if (post.id === action.payload.id) {
post.title = action.payload.title;
post.body = action.payload.body;
}
});
})
.addCase(updatePost.rejected, (state, action) => {
state.isLoading = false;
state.isError = true;
state.message = action.payload;
});
},
});
export const { reset } = postSlice.actions;
export default postSlice.reducer;
And, This is blogService
import Axios from "axios";
const api_Link = "http://localhost:8080/";
const getAllPosts = async () => {
const response = await Axios.get(api_Link + `blogs`);
const data = response.data.data;
return data;
};
const getSinglePost = async (id) => {
const response = await Axios.get(api_Link + `blogs/` + id);
const data = response.data.data;
return data;
};
const deletePost = async (id) => {
const response = await Axios.delete(api_Link + `blogs/` + id);
const data = response.data;
return data;
};
const editPost = async (id, { title, body }) => {
const response = await Axios.put(api_Link + `blogs/` + id, {
title,
body,
});
const data = response.data;
console.log(data);
return data;
};
const blogService = {
getAllPosts,
getSinglePost,
deletePost,
editPost,
};
export default blogService;
And, finally, this is the edit Page:
import React from "react";
import { useEffect } from "react";
import { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate, useParams } from "react-router-dom";
import { updatePost } from "../features/blogs/postSlice";
const Editpage = () => {
const params = useParams();
const navigate = useNavigate();
const dispatch = useDispatch();
console.log(params.id);
const handleSubmit = (e) => {
e.preventDefault();
dispatch(updatePost(params.id, { title: "This is title", body: "This is body" }));
};
return (
<>
<div className="container">
<div className="edit_Section">
<h1 className="text-center p-3 text-danger bg-light">Edit The Post</h1>
<div className="myForm d-flex justify-content-center bg-secondary text-light p-5">
<form className="w-50 border border-primary p-5 bg-primary">
<div className="mb-3">
<label htmlFor="postTitle" className="form-label">
Post Title
</label>
<input
type="text"
name="title"
value={postTitle}
onChange={(e) => setTitle(e.target.value)}
className="form-control"
id="postTitle"
/>
</div>
<div className="mb-3">
<label htmlFor="postTitle" className="form-label">
Post Body
</label>
<textarea
className="form-control"
value={postBody}
onChange={(e) => setBody(e.target.value)}
name="body"
id="postBody"
rows="10"
></textarea>
</div>
<button type="submit" className="btn btn-success" id={params.id} onClick={handleSubmit}>
Save Changes
</button>
</form>
</div>
</div>
</div>
</>
);
};
export default Editpage;
My primary objective is to update my mongodb post collection. I can create, delete and read. Only, updating db via React Redux is the issue I couldn't fix myself. It says, state is undefined in the postslice page. I'm not sure how to get that state to work.
Related
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.
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.
I am creating a simple app to play with Redux ToolKit along react; however, I can see the object in the redux chrome tab, but unable to access it through components using react hooks.
My slice:
import {
createSlice,
createSelector,
createAsyncThunk,
} from "#reduxjs/toolkit";
const initialState = {
cryptoList: [],
loading: false,
hasErrors: false,
};
export const getCryptos = createAsyncThunk("cryptos/get", async (thunkAPI) => {
try {
const cryptosUrl =
"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd";
let response = await fetch(cryptosUrl);
console.log(response);
return await response.json();
} catch (error) {
console.log(error);
}
});
const cryptoSlice = createSlice({
name: "cryptos",
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(getCryptos.pending, (state) => {
state.loading = true;
});
builder.addCase(getCryptos.fulfilled, (state, { payload }) => {
state.loading = false;
state.cryptoList = payload;
});
builder.addCase(getCryptos.rejected, (state, action) => {
state.loading = false;
state.hasErrors = action.error.message;
});
},
});
export const selectCryptos = createSelector(
(state) => ({
cryptoList: state.cryptoList,
loading: state.loading,
}),
(state) => state
);
export default cryptoSlice;
My component:
import React, { useEffect } from "react";
import { getCryptos, selectCryptos } from "./cryptoSlice";
import { useSelector, useDispatch } from "react-redux";
const CryptoComponent = () => {
const dispatch = useDispatch();
const { cryptoList, loading, hasErrors } = useSelector(selectCryptos);
useEffect(() => {
dispatch(getCryptos());
}, [dispatch]);
const renderCrypto = () => {
if (loading) return <p>Loading Crypto...</p>;
if (hasErrors) return <p>Error loading news...</p>;
if (cryptoList) {
return cryptoList.data.map((crypto) => <p> {crypto.id}</p>);
}
};
return (
<div className="container">
<div className="row">CryptoComponent: {renderCrypto()}</div>
</div>
);
};
export default CryptoComponent;
All constructed values from the state: cryptoList, loading, hasErrors, seem to be undefined at the component level.
Any suggestions are appreciated!
Have you tried using the following createSelector code:
export const selectCryptos = createSelector(
(state) => state,
(state) => ({
cryptoList: state.cryptoList,
loading: state.loading,
})
);
As per documentation state should be the first parameter:
https://redux.js.org/usage/deriving-data-selectors
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
Another newbie propblem. I want to post a post with my form. I have Post.js that looks like this:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import PostForm from './PostFormContainer';
export class Post extends Component {
static propTypes = {
posts: PropTypes.any,
fetchPosts: PropTypes.func,
sendPostData: PropTypes.func,
};
componentDidMount() {
const { fetchPosts } = this.props;
fetchPosts();
}
// onSubmit = (e, id, title, body) => {
// e.preventDefault();
// axios
// .post('https://jsonplaceholder.typicode.com/posts', {
// id,
// title,
// body,
// })
// .then(res =>
// this.setState({
// posts: [...this.state.posts, res.data],
// })
// );
// };
// onSubmit(e, id, title, body) {
// e.preventDefault();
// console.log('data');
// console.log('data', id);
// console.log('data', title);
// console.log('data', body);
// this.props.sendPostData(id, title, body);
// console.log('sendPostData', this.props.sendPostData(id, title, body));
// }
render() {
console.log('props', this.props);
const { posts } = this.props;
if (!posts.length) {
return (
<div>
<PostForm addPost={this.onSubmit} />
</div>
);
} else {
return (
<div>
<PostForm addPost={this.onSubmit} />
<br />
<div>
{posts.map(post => (
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
))}
;
</div>
</div>
);
}
}
}
export default Post;
Where I have <PostForm addPost={this.onSubmit} />
My PostForm.js looks like this:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class PostForm extends Component {
///state = {
// title: '',
// body: '',
//};
static propTypes = {
posts: PropTypes.any,
// fetchPosts: PropTypes.func,
sendPostData: PropTypes.func,
};
//onChange = e => {
//this.setState({
// e.target.name zawsze będzie targetował pole z value i zmieniał jego stan
// [e.target.name]: e.target.value,
// });
//};
// onSubmit(e, id, title, body) {
// e.preventDefault();
// console.log('data');
// console.log('data', id);
// console.log('data', title);
// console.log('data', body);
// }
onSubmit(e, id, title, body) {
e.preventDefault();
console.log('data');
console.log('data', id);
console.log('data', title);
console.log('data', body);
// const post = {
// title,
// body,
// };
this.props.sendPostData(title, body);
// console.log('sendPostData', this.props.sendPostData(post));
}
render() {
console.log('props form', this.props);
const { title, body } = this.props;
return (
<div>
<h1> Add Post </h1>
<form onSubmit={e => this.onSubmit(e, title, body)}>
<div>
<label>Title: </label>
<input
type='text'
name='title'
value={title}
onChange={this.onChange}
/>
</div>
<div>
<label>Body: </label>
<textarea name='body' value={body} onChange={this.onChange} />
</div>
<button type='submit'>Submit</button>
</form>
</div>
);
}
}
export default PostForm;
Here I want to send this with my action.
I have two container files
PostFormContainer.js
import { connect } from 'react-redux';
import PostForm from './PostForm';
import { sendPost } from '../reducers/postReducers';
const mapStateToProps = state => ({
posts: state.posts,
});
const mapDispatchToProps = dispatch => ({
sendPostData: post => dispatch(sendPost(post)),
});
export default connect(mapStateToProps, mapDispatchToProps)(PostForm);
and PostContainer.js
import { connect } from 'react-redux';
import Post from './Post';
import { fetchFromApi } from '../reducers/postReducers';
const mapStateToProps = state => ({
posts: state.posts,
});
const mapDispatchToProps = dispatch => ({
fetchPosts: () => dispatch(fetchFromApi()),
// sendPostData: (id, title, body) => dispatch(sendPost({ id, title, body })),
});
export default connect(mapStateToProps, mapDispatchToProps)(Post);
and my reducer
import Axios from 'axios';
const reducerName = 'posts';
const createActionName = name => `/${reducerName}/${name}`;
/* action type */
const FETCH_POSTS = createActionName('FETCH_POSTS');
const SUBMIT_POST = createActionName('SUBMIT_POST');
/* action creator */
export const fetchStarted = payload => ({ payload, type: FETCH_POSTS });
export const submitPost = payload => ({ payload, type: SUBMIT_POST });
/* thunk */
export const fetchFromApi = () => {
return (dispatch, getState) => {
Axios.get('https://jsonplaceholder.typicode.com/posts?_limit=5').then(
res => dispatch(fetchStarted(res.data))
// console.log('res', res)
// console.log('res data', res.data)
);
};
};
export const sendPost = (postId, postTitle, postBody) => {
return (dispatch, getState) => {
Axios.post('https://jsonplaceholder.typicode.com/posts', {
id: postId,
title: postTitle,
body: postBody,
}).then(res => {
dispatch(submitPost(res.data));
});
};
};
/* reducer */
export default function reducer(state = [], action = {}) {
switch (action.type) {
case FETCH_POSTS:
return action.payload;
case SUBMIT_POST: {
return {
...state,
data: action.payload,
};
}
default:
return state;
}
}
Right now my console.logs shows that all my data is undefined. Not sure what the I am missing, but I can't solve this.
Here is also my stro.js
import { combineReducers, applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
import postReducer from './reducers/postReducers';
const initialState = {
posts: {
data: {},
},
};
const reducers = {
posts: postReducer,
};
Object.keys(initialState).forEach(item => {
if (typeof reducers[item] == 'undefined') {
reducers[item] = (state = null) => state;
}
});
const combinedReducers = combineReducers(reducers);
const store = createStore(
combinedReducers,
initialState,
composeWithDevTools(applyMiddleware(thunk))
);
export default store;
Your PostForm element uses props title and body, but the place where you use PostForm doesn't send it a body or title prop.
I don't know your particular use case, but in React/Redux there are two ways to send a property to an element:
<PostForm body={this.state.postFormBody} title={this.state.postFormTitle} />
Or by using your Redux connector, mapStateToProps function, and returning an object with 'body' and 'title' keys that match something in your Redux store