Conditions | 15 |
Total Lines | 95 |
Code Lines | 75 |
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"; |
||
114 | |||
115 | export function useResource<T>( |
||
116 | endpoint: string, |
||
117 | initialValue: T, |
||
118 | overrides?: { |
||
119 | parseResponse?: (response: Json) => T; // Defaults to the identity function. |
||
120 | skipInitialFetch?: boolean; // Defaults to false. Override if you want to keep the initialValue until refresh is called manually. |
||
121 | 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. |
||
122 | }, |
||
123 | ): UseResourceReturnType<T> { |
||
124 | const parseResponse = overrides?.parseResponse ?? identity; |
||
125 | const doInitialRefresh = overrides?.skipInitialFetch !== true; |
||
126 | const handleError = overrides?.handleError ?? doNothing; |
||
127 | const isSubscribed = useRef(true); |
||
128 | |||
129 | const [state, dispatch] = useReducer< |
||
130 | Reducer<ResourceState<T>, AsyncAction<T>> |
||
131 | >(reducer, initialState(initialValue)); |
||
132 | |||
133 | const refresh = useCallback(async (): Promise<T> => { |
||
134 | dispatch({ type: ActionTypes.GetStart }); |
||
135 | let json: Json; |
||
136 | try { |
||
137 | json = await getRequest(endpoint).then(processJsonResponse); |
||
138 | } catch (error) { |
||
139 | if (isSubscribed.current) { |
||
140 | dispatch({ |
||
141 | type: ActionTypes.GetReject, |
||
142 | payload: error, |
||
143 | }); |
||
144 | handleError(error); |
||
145 | } |
||
146 | throw error; |
||
147 | } |
||
148 | const responseValue = parseResponse(json) as T; |
||
149 | if (isSubscribed.current) { |
||
150 | dispatch({ |
||
151 | type: ActionTypes.GetFulfill, |
||
152 | payload: responseValue, |
||
153 | }); |
||
154 | } |
||
155 | return responseValue; |
||
156 | }, [endpoint, parseResponse, handleError]); |
||
157 | |||
158 | const update = useCallback( |
||
159 | async (newValue): Promise<T> => { |
||
160 | dispatch({ type: ActionTypes.UpdateStart, meta: { item: newValue } }); |
||
161 | let json: Json; |
||
162 | try { |
||
163 | json = await putRequest(endpoint, newValue).then(processJsonResponse); |
||
164 | } catch (error) { |
||
165 | if (isSubscribed.current) { |
||
166 | dispatch({ |
||
167 | type: ActionTypes.UpdateReject, |
||
168 | payload: error, |
||
169 | meta: { item: newValue }, |
||
170 | }); |
||
171 | handleError(error); |
||
172 | } |
||
173 | throw error; |
||
174 | } |
||
175 | const responseValue = parseResponse(json) as T; |
||
176 | if (isSubscribed.current) { |
||
177 | dispatch({ |
||
178 | type: ActionTypes.UpdateFulfill, |
||
179 | payload: responseValue, |
||
180 | meta: { item: newValue }, |
||
181 | }); |
||
182 | } |
||
183 | return responseValue; |
||
184 | }, |
||
185 | [endpoint, parseResponse, handleError], |
||
186 | ); |
||
187 | |||
188 | // Despite the usual guidlines, this should only be reconsidered if endpoint changes. |
||
189 | // Changing doInitialRefresh after the first run (or the refresh function) should not cause this to rerun. |
||
190 | useEffect(() => { |
||
191 | if (doInitialRefresh) { |
||
192 | refresh().catch(doNothing); |
||
193 | } |
||
194 | |||
195 | // Unsubscribe from promises when this hook is unmounted. |
||
196 | return (): void => { |
||
197 | isSubscribed.current = false; |
||
198 | }; |
||
199 | |||
200 | // eslint-disable-next-line react-hooks/exhaustive-deps |
||
201 | }, [endpoint]); |
||
202 | |||
203 | return { |
||
204 | value: state.value, |
||
205 | status: state.status, |
||
206 | error: state.error, |
||
207 | update, |
||
208 | refresh, |
||
209 | }; |
||
213 |