fixed bug auth
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
import { createContext, useCallback, useContext, useEffect, useReducer } from "react";
|
||||
import useRequest from "../hooks/useRequest";
|
||||
import { GET_USER_ROUTE } from "@/core/utils/routes";
|
||||
import axios from "axios";
|
||||
import { createContext, useCallback, useContext, useEffect, useReducer } from "react";
|
||||
|
||||
const initAuth = {
|
||||
initAuthState: false,
|
||||
@@ -28,7 +28,6 @@ const AuthContext = createContext();
|
||||
|
||||
export const AuthProvider = ({ children }) => {
|
||||
const [state, dispatch] = useReducer(authReducer, initAuth);
|
||||
const request = useRequest();
|
||||
|
||||
const clearUser = useCallback(() => {
|
||||
dispatch({ type: "CLEAR_USER" });
|
||||
@@ -46,9 +45,15 @@ export const AuthProvider = ({ children }) => {
|
||||
dispatch({ type: "CHANGE_INIT_AUTH", initAuthState });
|
||||
}, []);
|
||||
|
||||
const logout = () => {
|
||||
clearUser();
|
||||
changeAuthState(false);
|
||||
changeInitAuth(true);
|
||||
}
|
||||
|
||||
const getUser = useCallback(async () => {
|
||||
try {
|
||||
const { data } = await request(GET_USER_ROUTE, "get");
|
||||
const { data } = await axios.get(GET_USER_ROUTE, { withCredentials: true });
|
||||
changeUser(data);
|
||||
changeAuthState(true);
|
||||
changeInitAuth(true);
|
||||
@@ -72,6 +77,7 @@ export const AuthProvider = ({ children }) => {
|
||||
isAuth: state.isAuth,
|
||||
initAuthState: state.initAuthState,
|
||||
getUser,
|
||||
logout
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { errorResponse } from "@/core/utils/errorResponse";
|
||||
import { GET_CSRF } from "@/core/utils/routes";
|
||||
import { successRequest } from "@/core/utils/successRequest";
|
||||
import axios from "axios";
|
||||
import { useAuth } from "../contexts/auth";
|
||||
|
||||
const getCsrfToken = async () => {
|
||||
try {
|
||||
@@ -26,6 +27,7 @@ const defaultOptions = {
|
||||
};
|
||||
|
||||
const useRequest = (initOptions) => {
|
||||
const { logout } = useAuth()
|
||||
const instance = axios.create();
|
||||
instance.interceptors.request.use(
|
||||
async function (config) {
|
||||
@@ -60,7 +62,7 @@ const useRequest = (initOptions) => {
|
||||
errorResponse(
|
||||
error.response,
|
||||
mergedOptions.notification.show && mergedOptions.notification.failed,
|
||||
"request_data"
|
||||
"request_data", logout
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
|
||||
Reference in New Issue
Block a user