#reactjs #react-native #react-redux #asyncstorage
#reactjs #react-native #react-redux #asyncstorage
Вопрос:
Итак, у меня есть мобильное приложение в react native, для которого я пытаюсь правильно создать поток аутентификации.Сначала у меня было это как веб-приложение, а теперь я пытаюсь сделать то же самое как мобильное приложение. Я использую redux для управления состоянием.
Вот каков процесс: как только пользователь входит в систему или регистрируется, я отправляю данные на серверную часть с помощью axios. Серверная часть генерирует токен пользователя. Я хотел бы создать систему, в которой я мог бы извлекать токен при входе пользователя в систему и хранить его с помощью AsyncStorage, чтобы я мог напрямую войти в систему пользователя, когда он или она попытается снова открыть приложение.
Вот код, более чем рад ответить на любые вопросы, это было сделано с помощью учебника react на самом деле:
LoginScreen.js
const Login = ( { navigation }) =gt; { const [email, setEmail] = useState(); const [password, setPassword] = useState(); const [message, setMessage] = useState(null) // Errors const [EmailMessage, setEmailMessage] = useState(null); const [PasswordMessage, setPasswordMessage] = useState(null); const dispatch = useDispatch(); const userLogin = useSelector((state) =gt; state.userLogin); const { loading, error, userInfo } = userLogin useEffect(() =gt; { if (userInfo) { navigation.navigate('MainTabs', { screen: 'Home'}); } }, [navigation, userInfo]); const submitHandler = (e) =gt; { e.preventDefault(); if (!email) { alert('Please fill in the email'); return }; if (!password) { alert('Please fill in the password'); return } dispatch(login(email, password)); };
Возвращаемая часть-это код интерфейса, который был оставлен без внимания для краткости
Теперь часть переделки:
userActions.js
import axios from "axios"; import { USER_LOGIN_FAIL, USER_LOGIN_REQUEST, USER_LOGIN_SUCCESS, USER_LOGOUT, USER_REGISTER_FAIL, USER_REGISTER_SUCCESS, USER_REGISTER_REQUEST } from "../constants/userConstants" import AsyncStorage from '@react-native-async-storage/async-storage'; export const login = (email, password) =gt; async(dispatch) =gt; { try { dispatch({ type: USER_LOGIN_REQUEST }); const config = { headers: { "Content-type": "application/json" } } const {data} = await axios.post("api/url", {email, password}, config) dispatch({type: USER_LOGIN_SUCCESS, payload:data}); await AsyncStorage.setItem("userInfo", JSON.stringify(data)) } catch (error) { dispatch({ type: USER_LOGIN_FAIL, payload: error.response amp;amp; error.response.data.message ? error.response.data.message : error.message, }) console.log("This login attempt is unsuccessful"); } } export const logout = () =gt; async (dispatch) =gt; { await AsyncStorage.removeItem("userInfo") dispatch({ type: USER_LOGOUT }); }; export const register = (full_name, email, password, social) =gt; async(dispatch) =gt; { try { dispatch({type: USER_REGISTER_REQUEST}); const config = { headers: { "Content-type": "application/json" } }; const {data} = await axios.post("api/url", {full_name, email, password, social}, config); dispatch({ type: USER_REGISTER_SUCCESS, payload: data}); dispatch({ type: USER_LOGIN_SUCCESS, payload: data}); await AsyncStorage.setItem("userInfo", JSON.stringify(data)) } catch (error) { dispatch({type: USER_REGISTER_FAIL, payload: error.response amp;amp; error.response.data.message ? error.response.data.message : error.message }) }}
userReducers.js
import { USER_LOGIN_REQUEST, USER_REGISTER_FAIL, USER_REGISTER_REQUEST, USER_REGISTER_SUCCESS } from "../constants/userConstants"; import { USER_LOGIN_SUCCESS, USER_LOGIN_FAIL, USER_LOGOUT } from "../constants/userConstants"; export const userLoginReducer = (state = {}, action) =gt; { 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; } } export const userRegisterReducer = (state = {}, action) =gt; { switch (action.type) { case USER_REGISTER_REQUEST: return {loading:true} case USER_REGISTER_SUCCESS: return {loading:false, userInfo: action.payload} case USER_REGISTER_FAIL: return {loading:false, error: action.payload} default: return state; } }
store.js
import { createStore, combineReducers, applyMiddleware } from 'redux'; import thunk from "redux-thunk"; import { userLoginReducer, userRegisterReducer } from './src/redux/reducers/userReducers'; import AsyncStorage from '@react-native-async-storage/async-storage'; const reducer = combineReducers({ //contains reducers userLogin: userLoginReducer, userRegister: userRegisterReducer }); const middleware = [thunk]; const getData = async () =gt; { try { const value = await AsyncStorage.getItem("userInfo") return value != null ? JSON.parse(value) : null; } catch(e) { console.log("this attempt is not successful"); } } const userInfoFromStorage = getData() || null; alert(JSON.stringify(userInfoFromStorage)) const initialState = { userLogin: {userInfo: userInfoFromStorage} }; const store = createStore( reducer, initialState, applyMiddleware(...middleware) ); export default store
I would appreciate any help here as I am not able to resolve how to solve this is this is a promise issue on fetch or something more general than that. I have a token generated in the backend once I register a user. I would really appreciate if anyone knows of the best way on how to fetch and save that token and log the user in if the user had already logged in