useStream refactoring (#40)

This commit is contained in:
Kilin Mikhail
2020-12-28 20:03:06 +03:00
committed by GitHub
parent 45a7694e64
commit 5664469b55
8 changed files with 109 additions and 39 deletions

View File

@ -8,22 +8,31 @@ type User = {
first_name: string;
last_name: string;
};
type Support = {
text: string;
url: string;
};
type UserReponse = {
data: Array<User>;
page: number;
per_page: number;
support: {
text: string;
url: string;
}
support: Support;
total: number;
total_pages: number;
};
type UserFindResponse = {
data: User;
support: Support;
}
const ROOT_URL = 'https://reqres.in/api/users';
export const usersApi = makeApi({
request: async () => {
const {data} = await http.get<void, UserReponse>('https://reqres.in/api/users');
const {data} = await http.get<void, UserReponse>(ROOT_URL);
return data;
},
findById: async (id: string) => {
const {data} = await http.get<void, UserFindResponse>(`${ROOT_URL}/${id}`);
return data;
}
});

View File

@ -1,7 +1,7 @@
import React, {ReactNode} from 'react';
import {RemoteData, fold, map} from '@devexperts/remote-data-ts';
import {RemoteData, fold, map as remoteDateMap} from '@devexperts/remote-data-ts';
import {Stream} from '@most/types';
import * as M from '@most/core';
import {map} from '@most/core';
import {pipe} from 'fp-ts/lib/pipeable';
export const renderAsyncData = <E, A>(
@ -20,7 +20,7 @@ export const mapRD = <E, A, R>(mapper: (val: A) => R) => {
return (stream$: Stream<RemoteData<E, A>>): Stream<RemoteData<E, R>> => {
return pipe(
stream$,
M.map(val => map(mapper)(val))
map(val => remoteDateMap(mapper)(val))
);
};
};

View File

@ -1,32 +1,33 @@
import {Sink, Stream} from '@most/types';
import {noop} from 'lodash';
import {useEffect, useState} from 'react';
import {Stream, Sink} from '@most/types';
import {newDefaultScheduler} from '@most/scheduler';
import {pending, RemoteData} from '@devexperts/remote-data-ts';
// eslint-disable-next-line
const emptyFunc = () => {};
export const useStream = <T>(stream$: Stream<T>, defaultValue: T): T => {
const [state, setState] = useState(defaultValue);
export function useStream<T extends Array<unknown>, R>(
piping: () => Stream<R>,
props: T,
) {
const [state, setState] = useState<R>();
useEffect(() => {
const sink: Sink<T> = {
setState(undefined);
// eslint-disable-next-line
}, props);
useEffect(() => {
const effect$ = piping();
const sink: Sink<R> = {
event: (_, val) => {
setState(val);
},
end: emptyFunc,
error: emptyFunc
end: noop,
error: noop
};
const unsub = effect$.run(sink, newDefaultScheduler());
const effect$ = stream$.run(sink, newDefaultScheduler());
return () => {
effect$.dispose();
unsub.dispose();
};
}, [stream$]);
// eslint-disable-next-line
}, props);
return state;
};
export const useStreamRD = <T, E = Error>(stream$: Stream<RemoteData<E, T>>): RemoteData<E, T> => {
return useStream(stream$, pending);
};
}