Я использую https://github.com/flatlogic/react-material-admin, который является React Admin Console
базой на Material UI
и дизайном с реагированием context
и hooks
.
В проекте определен контекст для пользователя UserContext.js
код прост (https://raw.githubusercontent.com/flatlogic/react-material-admin/master/src/context/UserContext.js):
import React from "react";
var UserStateContext = React.createContext();
var UserDispatchContext = React.createContext();
function userReducer(state, action) {
switch (action.type) {
case "LOGIN_SUCCESS":
return { ...state, isAuthenticated: true };
case "SIGN_OUT_SUCCESS":
return { ...state, isAuthenticated: false };
default: {
throw new Error(`Unhandled action type: ${action.type}`);
}
}
}
function UserProvider({ children }) {
var [state, dispatch] = React.useReducer(userReducer, {
isAuthenticated: !!localStorage.getItem("id_token"),
});
return (
<UserStateContext.Provider value={state}>
<UserDispatchContext.Provider value={dispatch}>
{children}
</UserDispatchContext.Provider>
</UserStateContext.Provider>
);
}
function useUserState() {
var context = React.useContext(UserStateContext);
if (context === undefined) {
throw new Error("useUserState must be used within a UserProvider");
}
return context;
}
function useUserDispatch() {
var context = React.useContext(UserDispatchContext);
if (context === undefined) {
throw new Error("useUserDispatch must be used within a UserProvider");
}
return context;
}
export { UserProvider, useUserState, useUserDispatch, loginUser, signOut };
// ###########################################################
function loginUser(dispatch, login, password, history, setIsLoading, setError) {
setError(false);
setIsLoading(true);
if (!!login && !!password) {
setTimeout(() => {
localStorage.setItem('id_token', 1)
setError(null)
setIsLoading(false)
dispatch({ type: 'LOGIN_SUCCESS' })
history.push('/app/dashboard')
}, 2000);
} else {
dispatch({ type: "LOGIN_FAILURE" });
setError(true);
setIsLoading(false);
}
}
function signOut(dispatch, history) {
localStorage.removeItem("id_token");
dispatch({ type: "SIGN_OUT_SUCCESS" });
history.push("/login");
}
Как видите, код loginUser
является фиктивным и не вызывает API. Я попытался использовать api fetch с крючком для подключения к серверу. Я использовал swr
(https://github.com/zeit/swr), который кажется простым
`....useSWR('/api/login'); ...`
Я получил ошибку:
React Hook "useSWR" is called in function "loginUser" which is neither a React
function component or a custom React Hook function react-hooks/rules-of-hooks
Кажется, я не могу поставить принеси сюда Но по логике это место, где оно должно быть!
Как я могу использовать swr
или здесь?!