Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 10 additions & 19 deletions src/async-data/AsyncView.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import React from 'react'
import { isFunction } from '../util'
import { AsyncState } from '../index'
import { getAsyncState } from './asyncState'

type LoadingFunction = () => React.ReactElement<any, any> | null
type SuccessFunction<Data> = (data: Data) => React.ReactElement<any, any> | null
Expand All @@ -27,23 +25,16 @@ const AsyncView = <Data, Error>(
renderSuccess,
renderError = null,
} = props
const asyncState = getAsyncState(data, error)

switch (asyncState) {
case AsyncState.FETCHING:
return isFunction(renderLoading) ? renderLoading() : <>{renderLoading}</>
case AsyncState.FINISHED_WITH_SUCCESS:
return isFunction(renderSuccess) ? (
renderSuccess(data as Data)
) : (
<>{renderSuccess}</>
)
case AsyncState.FINISHED_WITH_ERROR:
return isFunction(renderError) ? (
renderError(error as Error)
) : (
<>{renderError}</>
)
if (error != null && error != undefined) {
return isFunction(renderError) ? renderError(error) : <>{renderError}</>
} else if (data != null && data != undefined) {
return isFunction(renderSuccess) ? (
renderSuccess(data)
) : (
<>{renderSuccess}</>
)
} else {
return isFunction(renderLoading) ? renderLoading() : <>{renderLoading}</>
}
}

Expand Down
10 changes: 10 additions & 0 deletions src/async-data/asyncState.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
/**
* @deprecated Consider directly checking data and error values instead.
* Using `AsyncState` leads to unnecessary complexity and may disable type
* inference.
*/
enum AsyncState {
FETCHING,
FINISHED_WITH_ERROR,
FINISHED_WITH_SUCCESS,
}

/**
* @deprecated Consider directly checking data and error values instead.
* Using `AsyncState` leads to unnecessary complexity and may disable type
* inference.
*/
const getAsyncState = (data: unknown, error: unknown): AsyncState => {
if (error != null && error != undefined) {
return AsyncState.FINISHED_WITH_ERROR
Expand Down