Skip to content

Commit d37f28b

Browse files
author
devgioele
committed
simplify AsyncView
1 parent 6185ceb commit d37f28b

2 files changed

Lines changed: 20 additions & 19 deletions

File tree

src/async-data/AsyncView.tsx

Lines changed: 10 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
import React from 'react'
22
import { isFunction } from '../util'
3-
import { AsyncState } from '../index'
4-
import { getAsyncState } from './asyncState'
53

64
type LoadingFunction = () => React.ReactElement<any, any> | null
75
type SuccessFunction<Data> = (data: Data) => React.ReactElement<any, any> | null
@@ -27,23 +25,16 @@ const AsyncView = <Data, Error>(
2725
renderSuccess,
2826
renderError = null,
2927
} = props
30-
const asyncState = getAsyncState(data, error)
31-
32-
switch (asyncState) {
33-
case AsyncState.FETCHING:
34-
return isFunction(renderLoading) ? renderLoading() : <>{renderLoading}</>
35-
case AsyncState.FINISHED_WITH_SUCCESS:
36-
return isFunction(renderSuccess) ? (
37-
renderSuccess(data as Data)
38-
) : (
39-
<>{renderSuccess}</>
40-
)
41-
case AsyncState.FINISHED_WITH_ERROR:
42-
return isFunction(renderError) ? (
43-
renderError(error as Error)
44-
) : (
45-
<>{renderError}</>
46-
)
28+
if (error != null && error != undefined) {
29+
return isFunction(renderError) ? renderError(error) : <>{renderError}</>
30+
} else if (data != null && data != undefined) {
31+
return isFunction(renderSuccess) ? (
32+
renderSuccess(data)
33+
) : (
34+
<>{renderSuccess}</>
35+
)
36+
} else {
37+
return isFunction(renderLoading) ? renderLoading() : <>{renderLoading}</>
4738
}
4839
}
4940

src/async-data/asyncState.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,19 @@
1+
/**
2+
* @deprecated Consider directly checking data and error values instead.
3+
* Using `AsyncState` leads to unnecessary complexity and may disable type
4+
* inference.
5+
*/
16
enum AsyncState {
27
FETCHING,
38
FINISHED_WITH_ERROR,
49
FINISHED_WITH_SUCCESS,
510
}
611

12+
/**
13+
* @deprecated Consider directly checking data and error values instead.
14+
* Using `AsyncState` leads to unnecessary complexity and may disable type
15+
* inference.
16+
*/
717
const getAsyncState = (data: unknown, error: unknown): AsyncState => {
818
if (error != null && error != undefined) {
919
return AsyncState.FINISHED_WITH_ERROR

0 commit comments

Comments
 (0)