A small collection of utils and React components to assist in developing web applications that seamlessly work without JavaScript enabled on the client.
In short, by leveraging the similarities of form events and an event based state container like Redux, we can dispatch and update client/app state on the server side for users without JS enabled, by making all essential actions go through forms.
Instead of directly dispatching actions, we serialize the action type/creator and payload in the form body itself. The helpers in this package is meant to make this task easier.
More details on this can be found in "Using React, Redux and SSR to acommodate users without JavaScript", or this talk from React Advanced 2021.
npm i @wishy-gift/noscript
For these components to be of any use, you should be listening for POST
requests towards your view routes. One of the basic assumptions we make, is that the only reason why someone would do a POST-request to a view route is because they've disabled JS, and an action has been dispatched. This way we know when to update the client state for our users server-side, and re-render the page.
- _app.js for use with Next.js
- TodoMVC à la @wishy-gift/noscript
- Counter
- Epic Gutenberg
- Uses
createAsyncThunk
with a 3rd-party API (Gutendex)
- Uses
Will serialize the app state to the DOM, and handle client side state updates by calling preventDefault
when the form is submitted, parse the form data, and dispatch the correct action/actionCreator.
import Form from '@wishy-gift/noscript/dist/components/Form';
interface FormProps {
actionType?: string; // `type` to dispatch
actionCreator?: string | Function; // function or name of function. see section about actionCreators below
children: ReactNode;
className?: string;
onSubmit?: Function; // optional function to call on submit. NOTE: Actions are dispatched for you
payloadType?: 'string' | 'object' | 'json'; // default is 'object' which means you can use array notation like payload[foo][bar]
}
Note: You cannot specify both actionType
AND actionCreator
, but you can also omit passing any of them as props, instead opting to render it to the DOM like this:
<input name="actionType" value={someAction().type} type="hidden" readOnly />
<Form
className="new-todo-wrapper"
actionType={addTodo().type}
onSubmit={resetOnSubmit}
>
<input
className="new-todo"
name="payload[text]"
placeholder="What needs to be done?"
autoFocus
/>
<input type="hidden" name="payload[id]" value={nanoid()} />
</Form>
A simple wrapper for Form
with a <button>
as child and payloadType="json"
.
import Button from '@wishy-gift/noscript/dist/components/Button';
interface ButtonProps {
wrapperClassName?: string; // className to <Form>
wrapperParams?: object; // spread to <Form>
className?: string; // className for <button>
action?: {
type: string;
payload?: any; // will be stringifed and rendered to DOM if `payload` isn't provided
};
actionCreator?: string | Function; // function or name of function. see section about actionCreators below
payload?: any; // will be stringifed and rendered to DOM if provided
children: ReactNode;
onSubmit?: Function; // optional function to call on submit. NOTE: Actions are dispatched for you
}
Note: As with Form
, you cannot specify both action
AND actionCreator
.
<Button
className="btn"
actionCreator={fetchBooks}
disabled={!nextUrl}
payload={{
url: nextUrl,
}}
>
Next page
</Button>
Given a body and a callback for getting a Redux store given an initial state, will get the store, dispatch any action/actionCreator in body, and return the store and its updated state.
Returns a Promise
that resolves with {reduxStore, state}
import handleServerActions from '@wishy-gift/noscript/dist/utils/handleServerActions';
type HandleServerActionsParams = {
data: Data; // one of these must be provided
rawBody: string; // one of these must be provided
getReduxStore: (state: any) => ReturnType<typeof configureStore>;
};
type Data = {
actionType?: string;
actionCreatorName?: string;
payloadType: 'string' | 'object' | 'json';
state?: string;
payload?: any;
};
const rawBody = req.read().toString();
// const data = qs.parse(rawBody);
const result = await handleServerActions({
rawBody,
// data, // if pre-parsed
getReduxStore: (state) => {
return getStore(state, isServer);
},
});
const { reduxStore, state } = result;
Helpers for mapping actionCreators
to their typePrefix
and vice-versa. Specifically made to be compatible with thunks
created with createAsyncThunk
. Should be run once, eg. in _app.js
for Next.js projects.
import { addActionCreators } from '@wishy-gift/noscript/dist/utils/actionCreators';
// Basically the signature of an `AsyncThunk` created with `createAsyncThunk`
type SimpleActionCreator = Function & {
typePrefix?: string;
};
// _app.js
import { fetchBooks } from './gutenberg/gutenbergSlice';
import { incrementBySurprise } from './counter/counterSlice';
addActionCreators({ fetchBooks, incrementBySurprise });
A hook that returns a Proxy
to easier provide the corect array notation to the name
attribute of form elements by simply accessing the proxy.
import usePayloadProxy from '@wishy-gift/noscript/dist/hooks/usePayloadProxy';
varName?: string; // defaults to 'payload'
const MyInput = () => {
const payloadProxy = usePayloadProxy('payload'); // 'payload' is default
return <input name={payloadProxy.foo.bar} value="baz" type="text" />;
};
will render
<input name="payload[foo][bar]" value="baz" type="text" />
See LICENSE