質問編集履歴

1

該当コードの修正

2023/01/10 14:36

投稿

intron0113
intron0113

スコア14

test CHANGED
File without changes
test CHANGED
@@ -8,21 +8,74 @@
8
8
  - union型で定義したtypesを用いて型管理を行いたい
9
9
 
10
10
  ### 発生している問題・エラーメッセージ
11
- myPageSettingsの初期値とuseEffectのdefault値に正しく型定義を反映できていない
11
+ myPageSettingsの初期値に正しく型定義を反映できておらず、ユニオン型で定義した文字列以外も初期値に入力できてしまう
12
-
13
12
 
14
13
  ### 該当のソースコード
15
14
  型定義
16
15
  ```ts
16
+ //SelectType.ts
17
+
17
18
  export type SelectType = 'A' | 'B' | 'def';
18
19
 
20
+ ```
21
+ state管理
22
+ ```tsx
23
+ //useGlobalState.tsx
24
+
25
+ import {
26
+ SetStateAction,
27
+ createContext,
28
+ useContext,
29
+ useEffect,
30
+ useState,
31
+ } from 'react';
32
+ import { SelectType } from '@/types/SelectType';
33
+
34
+ export const GlobalContext = createContext({
35
+ selectType: 'hide' as SelectType,
36
+ setSelectType: (selectType: SetStateAction<SelectType>) => {
37
+ // dummy
38
+ },
39
+ });
40
+
41
+ export const GlobalContextProvider = ({
42
+ children,
43
+ }: {
44
+ children: JSX.Element | JSX.Element[];
45
+ }) => {
46
+ const context = useContext(GlobalContext);
47
+
48
+ const [selectType, setSelectType] = useState<SelectType>(
49
+ context.selectType
50
+ );
51
+
52
+ const value = {
53
+ selectType,
54
+ setSelectType,
55
+ };
56
+ return (
57
+ <GlobalContext.Provider value={value}>{children}</GlobalContext.Provider>
58
+ );
59
+ };
19
60
  ```
20
61
 
21
62
  該当ファイル
22
63
  ```tsx
64
+ //myPageSettings.tsx
65
+
66
+ import router from 'next/router';
67
+ import { useEffect } from 'react';
68
+
69
+ import { useGlobalState } from '@/useGlobalState';
70
+
71
+ import { SelectType } from '@/types/SelectType';
72
+ import { AppType } from '@/types/AppType';
73
+
74
+
75
+
23
76
  export const myPageSettings = ({
24
- // 初期値と型定義を行う 該当箇所1
25
77
  appType = AppType.Other as AppType,
78
+ // 初期値と型定義を行う 該当箇所
26
79
  selectType = 'def' as SelectType,
27
80
  }) => {
28
81
 
@@ -38,7 +91,6 @@
38
91
  setSelectType(selectType);
39
92
  break;
40
93
  default:
41
- // 条件に当てはまらなかった際の処理 該当箇所2
42
94
  setSelectType('def');
43
95
  }
44
96
  }