Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

trackedFunction is not composable with the use within a resource. #922

Closed
NullVoxPopuli opened this issue Jun 20, 2023 · 1 comment
Closed
Labels
bug Something isn't working

Comments

@NullVoxPopuli
Copy link
Owner

For example, this should be possible:

/**
 * A subset of the state provided by `trackedFunction`
 */
interface NormalizedState<Data> {
	value: Data | undefined;

	error: unknown;
	isError: boolean;

	isResolved: boolean;
	isPending: boolean;
	isRejected: boolean;
	isSettled: boolean;

	isLoading: boolean;
	isFinished: boolean;
}

class SimpleState<Data> implements NormalizedState<Data> {
	constructor(public value: Data) {}
	get isError() {
		return false;
	}
	get isResolved() {
		return true;
	}
	get isPending() {
		return false;
	}
	get isLoading() {
		return false;
	}
	get isRejected() {
		return false;
	}
	get isSettled() {
		return true;
	}
	get isFinished() {
		return true;
	}

	get error() {
		return null;
	}
}

function normalizedData<Data>(data: Promise<Data>): NormalizedState<Data>;
function normalizedData<Data>(data: () => Promise<Data>): NormalizedState<Data>;
function normalizedData<Data>(data: () => Data): NormalizedState<Data>;
function normalizedData<Data>(data: Data): NormalizedState<Data>;
function normalizedData<Data>(
	data: Data | (() => Data) | (() => Promise<Data>) | Promise<Data>,
): NormalizedState<Data> {
	/**
	 * This resource, itself, does not have any cleanup,
	 * but the underlying resources `use`d within do.
	 */
	return resource(({ use }) => {
		if (typeof data === 'function') {
			const state = use(trackedFunction(data));

			return () => state.current;
		}

		if (typeof data === 'object' && data !== null) {
			if ('then' in data) {
				const state = use(trackedFunction(async () => data));

				return () => state.current;
			}
		}

		return new SimpleState<Data>(data);
	});
}

export const NormalizedData = resourceFactory(normalizedData) as typeof normalizedData;
@NullVoxPopuli NullVoxPopuli added the bug Something isn't working label Jun 20, 2023
@NullVoxPopuli
Copy link
Owner Author

Implemented in #975

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant