0

I'm trying to build An Authenticated system and my user's state does not update with the values when logged in with ionic 5

Here go my reducers:

// eslint-disable-next-line import/no-anonymous-default-export
export default (state: any, action: any) => {
  switch (action.type) {
    case "LOGIN":
      return {
        ...state,
        user: { user: state.user, action: action.user },
      };

    case "REGISTER":
      return {
        ...state,
        user: { user: state.user, action: action.user },
      };
    case "USER_ERROR":
      return {
        ...state,
        error: action.payload,
      };
    default:
      return state;
  }
};

AuthContext

import React, { createContext, useContext, useReducer, useState } from "react";
import AuthReducer from "./reducers/AuthReducer";
import axios from "axios";
import { UserState } from "./types";
import { useHistory } from "react-router-dom";
import { Plugins } from "@capacitor/core";

// Initial State
const initialState: UserState = {
  user: {},
  error: null,
  loading: true,
  location: {},
  getLocation: () => {},
  UserLogin: () => {},
  UserRegister: () => {},
};

// Create Context
export const AuthContext = createContext<UserState>(initialState);

// Provider
export const AuthProvider: React.FC = ({ children }) => {
  const URL = "https://backend.com/api/v1/auth";
  const [state, dispatch] = useReducer(AuthReducer, initialState);
  const [location, setLocation] = useState<object>({ long: "", lat: "" });
  // const [user, setUser] = useState({})
  const { Toast, Geolocation } = Plugins;
  const history = useHistory();

  // Get Location
  const getLocation = async () => {
    try {
      const coordinates = await Geolocation.getCurrentPosition();
      const lat = coordinates.coords.latitude;
      const long = coordinates.coords.longitude;
      setLocation({
        long,
        lat,
      });
      console.log(location);
    } catch (error) {
      console.log(error);
    }
  };

  getLocation();

  // Login
  const UserLogin = async (user: any) => {
    try {
      const res = await axios.post(`${URL}/login`, user, {
        headers: { "Content-Type": "application/json" },
      });
      dispatch({
        type: "LOGIN",
        user: res.data,
      });
      console.log(res.data);
      await Toast.show({
        text: "Account created successfully",
        duration: "short",
        position: "bottom",
      });
      alert("Done");
      history.push("/dashboard");
    } catch (error) {
      dispatch({
        type: "USER_ERROR",
        payload: error.message,
      });
      console.log(error.message);
      await Toast.show({
        text: `${error.message}`,
        duration: "short",
        position: "bottom",
      });
    }
  };

  // Register
  const UserRegister = async (user: any) => {
    try {
      const res = await axios.post(`${URL}/signup`, user, {
        headers: { "Content-Type": "application/json" },
      });
      dispatch({
        type: "REGISTER",
        user: res.data,
      });
      console.log(res.data);
      await Toast.show({
        text: "Account created successfully",
        duration: "short",
        position: "bottom",
      });
      alert("Done");
      history.push("/login");
    } catch (error) {
      dispatch({
        type: "USER_ERROR",
        payload: error.message,
      });
      console.log(error.message);
      await Toast.show({
        text: `${error.message}`,
        duration: "short",
        position: "bottom",
      });
    }
  };

  return (
    <AuthContext.Provider
      value={{
        user: state.user,
        loading: state.loading,
        error: state.error,
        location,
        getLocation,
        UserLogin,
        UserRegister,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

I can see my location, but I can't see my user object, I think the way the state is constructed does not look nice.

The user's object is empty.

halfer
  • 19,824
  • 17
  • 99
  • 186
AbdulAzeez Olanrewaju
  • 976
  • 1
  • 13
  • 32
  • Your login and register actions are going to return state that looks like `{...state, user: {user: {}, action: action.user}}`. Is that really what you want? Seems like what you're after is `{...state, user: action.user}`. – lawrence-witt Feb 14 '21 at 00:30
  • {...state, user: {user: {}, action: action.user}} returns the state on the app but says State: undefined in the React dev tools – AbdulAzeez Olanrewaju Feb 14 '21 at 00:39

0 Answers0