I’m using React, Axios and Mongoose. Trying to store a user state but am having trouble with the stored state.user
object.
When I manually enter values for state.user
, the app works properly, however when I actually login from the site, the user object is stored in localStorage
but is not being read properly by the app. I noticed I had to remove new ObjectId
from the object and also convert the createdAt
and lastUpdated
dates into strings in order for my static values to work. How can I get around this? Thanks!
Screenshot of localStorage object
context.js
const INITIAL_STATE = {
user: JSON.parse(localStorage.getItem("user")) || null,
isFetching: false,
error: false,
};
export const AuthContext = createContext(INITIAL_STATE);
export const AuthContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(AuthReducer, INITIAL_STATE);
useEffect(() => {
JSON.stringify(localStorage.setItem("user", state.user));
}, [state.user]);
return (
<AuthContext.Provider
value={{
user: state.user,
isFetching: state.isFetching,
error: state.error,
dispatch,
}}
>
{children}
</AuthContext.Provider>
);
};
reducer.js
const AuthReducer = (state, action) => {
switch (action.type) {
case "LOGIN_START":
return {
user: null,
isFetching: true,
error: false,
};
case "LOGIN_SUCCESS":
return {
user: action.payload,
isFetching: false,
error: false,
};
case "LOGIN_FAILURE":
return {
user: null,
isFetching: false,
error: true,
};
case "FOLLOW":
return {
...state,
user: {
...state.user,
following: [...state.user.following, action.payload],
},
};
case "UNFOLLOW":
return {
...state,
user: {
...state.user,
following: state.user.following.filter(
(following) => following !== action.payload
),
},
};
default:
return state;
}
};
export default AuthReducer;
actions.js
export const LoginStart = (userCredentials) => ({
type: "LOGIN_START",
});
export const LoginSuccess = (user) => ({
type: "LOGIN_SUCCESS",
payload: user,
});
export const LoginFailure = (error) => ({
type: "LOGIN_FAILURE",
payload: error,
});
export const Follow = (userId) => ({
type: "FOLLOW",
payload: userId,
});
export const Unfollow = (userId) => ({
type: "UNFOLLOW",
payload: userId,
});
utils/api.js
import axios from "axios";
export const loginCall = async (userCredentials, dispatch) => {
dispatch({ type: "LOGIN_START" });
try {
const response = await axios.post("/api/auth/login", userCredentials);
dispatch({ type: "LOGIN_SUCCESS", payload: response.data });
} catch (error) {
dispatch({ type: "LOGIN_FAILURE", payload: error });
}
};