Bloc for React
This package is built to work with bloc.
Bloc Components
This is a fork version of felangel's bloc.js, contains a lot of workflow with dart version.
If you are familiar with dart bloc, this package would be your best friend!
A bundle of formz
, useBloc
, repository
, and a common used action_bloc
and search_bloc
. These should be indenpendent someday.
Formz example
`tsx import { FormzInput } from '@tokenyet/react-bloc';
export enum NameFieldError { empty, }
export class NameField extends FormzInput<string, NameFieldError> { pure() { super.pure(); this.value = ''; }
dirty(value: string) { super.dirty(value); }
validator(value: string | null): NameFieldError | null { if (value == null || value == '') return NameFieldError.empty; return null; } } `
useBloc example
const [formState, formBloc] = useBloc<
FormValidationBloc,
FormValdiationState,
FormValidationEvent
>(new FormValidationBloc(false));
Repository example (_app.tsx in Nextjs)
<RepoContext.Provider value={
new Repositories([
new UserRepository()
...any other repos
])}>
...
<ThemeProvider theme={theme}>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
<Component {...pageProps} />
</ThemeProvider>
...
</RepoContext.Provider>
Action Bloc example
// extend it to define props and what data will receive
import { ActionBloc, ActionEvent, ActionState } from '@tokenyet/react-bloc';
export interface LoginProps {
name: string;
picture: string;
password: string;
}
export class LoginActionBloc extends ActionBloc<LoginProps, null> {}
export class LoginActionEvent extends ActionEvent<LoginProps> {}
export class LoginActionState extends ActionState<null> {}
// use it in code
const router = useRouter();
const repoContext = useContext(RepoContext);
const userRepo = repoContext.of<UserRepository>(UserRepository);
const [signupAcitonState, signupActionBloc] = useBloc<
LoginActionBloc,
LoginActionState,
LoginActionEvent
>(
new LoginActionBloc(async ({ name, password, picture }) => {
await userRepo?.signup({ name, password, picture });
return {
value: null,
};
})
);
React.useEffect(() => {
if (signupAcitonState.status === FormzStatus.submissionSuccess) {
router.push('/home');
}
}, [signupAcitonState.status]);
Search Bloc
A bit complex, just use CommonSearchBloc
, and define your way to fetch data, and call PageEvent
or FetchEvent
to support Load More or Pagination feature. Might have an example someday.