Using Movex
Remeber, the state logic lives in the reducer, which only needs to be written once, at the client level, as if building a single player or front-end only app. Movex makes it possible to take the movex.js file, upload it on a server and run it as the authority, without you, the developer having to write any specific code or hooking up anything. (Except setting up the Movex Backend Service or using a hosting provider. But this should only be done once).
// counter.movex.ts
import { Action } from 'movex';
export type CounterState = {
count: number;
};
export const initialCounterState: CounterState = {
count: 0,
};
export type CounterActions =
| Action<'increment'>
| Action<'decrement'>
| Action<'incrementBy', number>;
export default (state = initialCounterState, action: CounterActions) => {
if (action.type === 'increment') {
return {
...state,
count: state.count + 1,
};
}
if (action.type === 'decrement') {
return {
...state,
count: state.count - 1,
};
}
if (action.type === 'incrementBy') {
return {
...state,
count: state.count + action.payload,
};
}
return state;
};
Define the movex.config. This is where the movex reducers get assigned a resource type.
// This will be read by both the client and the server
import counterReducer from './counter.movex';
export default {
resources: {
counter: counterReducer,
},
};
// App.ts
const movex = await new Promise((resolve) => {
Client.initMovex(
{
clientId,
url: props.socketUrl,
apiKey: '',
},
resolve
);
});
const conterResource = movex.registerResource(
'counter',
counterResourceReducer
);
// use it
const counterResourceIdentifier = conterResource.create();
// movex.resources is MovexResource({});
counterResource.onUpdated(counterResourceIdentifier, (nextState) => {
console.log('got next state', nextState);
});