اذهب إلى المحتوى

السؤال

نشر (معدل)

السلام عليكم .. أريد أن اعمل Authentication باستخدام Context API ولكنى تواجهنى مشكلة وهى لا اعرف ما سببها ولا تظهر لى اخطاء حتى ابحث عنها .. كل شء يعمل على ما يرام لكنى لا اعرف لمااذ عندما اقوم بادخال ايميل و اسم مستخدم صحيح فانه لا يقوم بعمل navigation 

اشعر ان الخطأ هنا فى هذا الموديول .. هذه هى صفحة تسجيل الدخول

import React, { useContext, useState, useEffect } from "react";
import { View } from "react-native";

import MyInput from "../components/MyInput";
import MyButton from "../components/MyButton";

// Context
import AuthGlobal from "../Context/store/AuthGlobal";
import { loginUser } from "../Context/actions/Auth.actions";

function LoginScreen({ navigation }) {
  const context = useContext(AuthGlobal);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [hidePass, setHidePass] = useState(false);

  useEffect(() => {
    if (context.stateUser.isAuthenticated === true) {
      navigation.navigate("profileScreen");
    }
  }, [context.stateUser.isAuthenticated]);

  const handleSubmit = () => {
    const user = {
      email,
      password,
    };

    if (email === "" || password === "") {
      console.log("Please fill in your credentials");
    } else {
      loginUser(user, context.dispatch);
    }
  };

  return (
    <View>
      <MyInput
        placeholder="email"
        iconName="email"
        onChangeText={(text) => setEmail(text)}
      />

      <MyInput
        secureTextEntry={hidePass}
        iconName="lock"
        placeholder="Password"
        IsPassword
        hideIconName={hidePass ? "eye" : "eye-off"}
        onPress={() => setHidePass(!hidePass)}
        onChangeText={(text) => setPassword(text)}
      />

      <MyButton title="Login" onPress={() => handleSubmit()} />

    </View>
  );
}

export default LoginScreen;


 

هذا هو الاكشن 

// Auth.actions.js


import jwt_decode from "jwt-decode";
import AsyncStorage from "@react-native-async-storage/async-storage";
import Toast from "react-native-toast-message";
import baseURL from "../../assets/common/baseUrl";

export const SET_CURRENT_USER = "SET_CURRENT_USER";

export const loginUser = (user, dispatch) => {
  fetch(`${baseURL}users/login`, {
    method: "POST",
    body: JSON.stringify(user),
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
  })
    .then((res) => res.json())
    .then((data) => {
      if (data) {
        const token = data.token;
        AsyncStorage.setItem("jwt", token);
        const decoded = jwt_decode(token);
        dispatch(setCurrentUser(decoded, user));
      } else {
        logoutUser(dispatch);
      }
    })
    .catch((err) => {
      Toast.show({
        topOffset: 60,
        type: "error",
        text1: "Please provide correct credentials",
        text2: "",
      });
      logoutUser(dispatch);
    });
};

export const getUserProfile = (id) => {
  fetch(`${baseURL}users/${id}`, {
    method: "GET",
    body: JSON.stringify(user),
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
  })
    .then((res) => res.json())
    .then((data) => console.log(data));
};

export const logoutUser = (dispatch) => {
  AsyncStorage.removeItem("jwt");
  dispatch(setCurrentUser({}));
};

export const setCurrentUser = (decoded, user) => {
  return {
    type: SET_CURRENT_USER,
    payload: decoded,
    userProfile: user,
  };
};

 

هذا هو الريديوسر

// Auth.reducer.js


import { SET_CURRENT_USER } from "../actions/Auth.actions"
import isEmpty from "../../assets/common/is-empty"

export default function (state, action) {
    switch (action.type) {
        case SET_CURRENT_USER: 
        return {
            ...state,
            isAuthenticated: !isEmpty(action.payload),
            user: action.payload,
            userProfile: action.userProfile
        };
        default:
            return state;
    }
}

 

هذا فى Store

// Auth.js in folder store

import React, { useEffect, useReducer, userEffect, useState } from "react";
import jwt_decode from "jwt-decode";
import AsyncStorage from "@react-native-async-storage/async-storage";

import authReducer from "../reducers/Auth.reducer";
import { setCurrentUser } from "../actions/Auth.actions";
import AuthGlobal from "./AuthGlobal";

const Auth = (props) => {
  const [stateUser, dispatch] = useReducer(authReducer, {
    isAuthenticated: null,
    user: {},
  });
  const [showChild, setShowChild] = useState(false);

  useEffect(() => {
    setShowChild(true);
    if (AsyncStorage.jwt) {
      const decoded = AsyncStorage.jwt ? AsyncStorage.jwt : "";
      if (setShowChild) {
        dispatch(setCurrentUserUser(jwt_decode(decoded)));
      }
    }
    return () => setShowChild(false);
  }, []);

  if (!showChild) {
    return null;
  } else {
    return (
      <AuthGlobal.Provider
        value={{
          stateUser,
          dispatch,
        }}
      >
        {props.children}
      </AuthGlobal.Provider>
    );
  }
};

export default Auth;

 

هذا ايضا فى store

// AuthGlobal.js in store folder

import React from "react";

export default React.createContext();

 

 

ملحوظة .. 
navigation , node apis وايضا ال forms كله يعمل بشكل صحيح حيث قمت باختبارهم

تم التعديل في بواسطة Ahmed Sawy

Recommended Posts

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...