@@ -15,31 +15,33 @@ type UserOSState = {
1515
1616const useDetectOS = ( ) => {
1717 const [ userOSState , setUserOSState ] = useState < UserOSState > ( {
18- os : detectOS ( ) ,
18+ os : 'LOADING' ,
1919 bitness : 64 ,
20- architecture : 'x64 ' ,
20+ architecture : '' ,
2121 } ) ;
2222
2323 useEffect ( ( ) => {
24- Promise . all ( [ getBitness ( ) , getArchitecture ( ) ] ) . then (
25- ( [ bitness , architecture ] ) => {
26- const userAgent : string | undefined =
27- ( typeof navigator === 'object' && navigator . userAgent ) || '' ;
28-
29- // Default bitness if unable to determine
30- const defaultBitness : number = 86 ;
31- // Regex to detect 64-bit architecture in user agent
32- const bitnessRegex = / W O W 6 4 | W i n 6 4 | x 8 6 _ 6 4 | x 8 6 - 6 4 | x 6 4 _ 6 4 | x 6 4 ; | A M D 6 4 / ;
33-
34- setUserOSState ( {
35- os : detectOS ( ) ,
36- bitness :
37- bitness === '64' || bitnessRegex . test ( userAgent )
38- ? 64
39- : defaultBitness ,
40- architecture : architecture ? architecture : '' ,
41- } ) ;
42- }
24+ // If the navigator User Agent indicates a 64-bit OS, we can assume the bitness is 64.
25+ const uaIndicates64 = / W O W 6 4 | W i n 6 4 | x 8 6 _ 6 4 | x 8 6 - 6 4 | x 6 4 _ 6 4 | x 6 4 ; | A M D 6 4 / . test (
26+ navigator . userAgent
27+ ) ;
28+
29+ // We immediately set the OS to LOADING, and then we update it with the detected OS.
30+ // This is due to that initial render set within the state will indicate a mismatch from
31+ // the server-side rendering versus what the initial state is from the client-side
32+ setUserOSState ( current => ( { ...current , os : detectOS ( ) } ) ) ;
33+
34+ // We then update the bitness based on the detected OS and the user agent
35+ getBitness ( ) . then ( ( bitness = '64' ) =>
36+ setUserOSState ( current => ( {
37+ ...current ,
38+ bitness : bitness === '64' || uaIndicates64 ? 64 : 86 ,
39+ } ) )
40+ ) ;
41+
42+ // We then update the architecture based on the detected OS
43+ getArchitecture ( ) . then ( ( architecture = '' ) =>
44+ setUserOSState ( current => ( { ...current , architecture } ) )
4345 ) ;
4446 } , [ ] ) ;
4547
0 commit comments