Conditions | 15 |
Total Lines | 101 |
Code Lines | 81 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
Complex classes like singleResourceHook.ts ➔ useResource often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
1 | import { Reducer, useCallback, useEffect, useReducer, useRef } from "react"; |
||
106 | |||
107 | export function useResource<T>( |
||
108 | endpoint: string, |
||
109 | initialValue: T, |
||
110 | overrides?: { |
||
111 | parseResponse?: (response: Json) => T; // Defaults to the identity function. |
||
112 | skipInitialFetch?: boolean; // Defaults to false. Override if you want to keep the initialValue until refresh is called manually. |
||
113 | handleError?: (error: Error | FetchError) => void; // In addition to using the error returned by the hook, you may provide a callback called on every new error. |
||
114 | }, |
||
115 | ): { |
||
116 | value: T; |
||
117 | status: ResourceStatus; |
||
118 | error: undefined | Error | FetchError; |
||
119 | update: (newValue: T) => Promise<T>; |
||
120 | refresh: () => Promise<T>; |
||
121 | } { |
||
122 | const parseResponse = overrides?.parseResponse ?? identity; |
||
123 | const doInitialRefresh = overrides?.skipInitialFetch !== true; |
||
124 | const handleError = overrides?.handleError ?? doNothing; |
||
125 | const isSubscribed = useRef(true); |
||
126 | |||
127 | const [state, dispatch] = useReducer< |
||
128 | Reducer<ResourceState<T>, AsyncAction<T>> |
||
129 | >(reducer, initialState(initialValue)); |
||
130 | |||
131 | const refresh = useCallback(async (): Promise<T> => { |
||
132 | dispatch({ type: ActionTypes.GetStart }); |
||
133 | let json: Json; |
||
134 | try { |
||
135 | json = await getRequest(endpoint).then(processJsonResponse); |
||
136 | } catch (error) { |
||
137 | if (isSubscribed.current) { |
||
138 | dispatch({ |
||
139 | type: ActionTypes.GetReject, |
||
140 | payload: error, |
||
141 | }); |
||
142 | handleError(error); |
||
143 | } |
||
144 | throw error; |
||
145 | } |
||
146 | const responseValue = parseResponse(json) as T; |
||
147 | if (isSubscribed.current) { |
||
148 | dispatch({ |
||
149 | type: ActionTypes.GetFulfill, |
||
150 | payload: responseValue, |
||
151 | }); |
||
152 | } |
||
153 | return responseValue; |
||
154 | }, [endpoint, parseResponse, handleError]); |
||
155 | |||
156 | const update = useCallback( |
||
157 | async (newValue): Promise<T> => { |
||
158 | dispatch({ type: ActionTypes.UpdateStart, meta: { item: newValue } }); |
||
159 | let json: Json; |
||
160 | try { |
||
161 | json = await putRequest(endpoint, newValue).then(processJsonResponse); |
||
162 | } catch (error) { |
||
163 | if (isSubscribed.current) { |
||
164 | dispatch({ |
||
165 | type: ActionTypes.UpdateReject, |
||
166 | payload: error, |
||
167 | meta: { item: newValue }, |
||
168 | }); |
||
169 | handleError(error); |
||
170 | } |
||
171 | throw error; |
||
172 | } |
||
173 | const responseValue = parseResponse(json) as T; |
||
174 | if (isSubscribed.current) { |
||
175 | dispatch({ |
||
176 | type: ActionTypes.UpdateFulfill, |
||
177 | payload: responseValue, |
||
178 | meta: { item: newValue }, |
||
179 | }); |
||
180 | } |
||
181 | return responseValue; |
||
182 | }, |
||
183 | [endpoint, parseResponse, handleError], |
||
184 | ); |
||
185 | |||
186 | // Despite the usual guidlines, this should only be reconsidered if endpoint changes. |
||
187 | // Changing doInitialRefresh after the first run (or the refresh function) should not cause this to rerun. |
||
188 | useEffect(() => { |
||
189 | if (doInitialRefresh) { |
||
190 | refresh().catch(doNothing); |
||
191 | } |
||
192 | |||
193 | // Unsubscribe from promises when this hook is unmounted. |
||
194 | return (): void => { |
||
195 | isSubscribed.current = false; |
||
196 | }; |
||
197 | |||
198 | // eslint-disable-next-line react-hooks/exhaustive-deps |
||
199 | }, [endpoint]); |
||
200 | |||
201 | return { |
||
202 | value: state.value, |
||
203 | status: state.status, |
||
204 | error: state.error, |
||
205 | update, |
||
206 | refresh, |
||
207 | }; |
||
211 |