-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathlogout.ts
More file actions
41 lines (33 loc) · 1.1 KB
/
logout.ts
File metadata and controls
41 lines (33 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { userInfoActions } from '../store/user-slice'
import Cookies from 'js-cookie'
import { NextRouter } from 'next/router'
import { Dispatch } from '@reduxjs/toolkit'
/**
* Comprehensive logout utility that clears all user data and caches
* @param dispatch Redux dispatch function
* @param router Next.js router
*/
export const logoutUser = (dispatch: Dispatch<any>, router: NextRouter) => {
// Clear Redux state
dispatch(userInfoActions.userLogout())
// Clear cookies
Cookies.remove('userInfo')
Cookies.remove('authToken')
// List of localStorage keys to preserve (if needed)
const keysToPreserve = ['userPhone']
const preservedData: Record<string, string | null> = {}
// Save data that needs to be preserved
keysToPreserve.forEach(key => {
preservedData[key] = localStorage.getItem(key)
})
// Clear all localStorage
localStorage.clear()
// Restore preserved data
Object.entries(preservedData).forEach(([key, value]) => {
if (value) localStorage.setItem(key, value)
})
// Clear session storage
sessionStorage.clear()
// Redirect to login page
router.push('/')
}