In Joystick, the cache()
method helps you to create a client-side, global state cache for your app (think like Redux but specific to Joystick). A cache can be initialized with a default value and returns an instance with methods for modifying the cache and listening for changes.
Global State
As a convenience, Joystick initializes a default cache for your app and exposes it via the named export global_state
from @joystick.js/ui
. global_state
is just an alias for the instance returned by the cache()
method documented below.
Example Usage
Inside of our App
layout component, we import cache
from @joystick.js/ui
and initialize our global state at window.player_state
.
To initialize our cache, we call cache('<cache_name>', <default_state>)
, here within the lifecycle.on_mount
method of our App
layout component:
ui/layouts/app/index.js
import joystick, { cache } from '@joystick.js/ui';
import Player from '../../components/player/index.js';
const App = joystick.component({
state: {
player: null,
},
lifecycle: {
on_mount: (instance = {}) => {
window.player_state = cache('player', {});
},
},
render: ({ component, props }) => {
return `
<div class="app">
${component(props.page, props)}
${component(Player, { state: state?.player })}
</div>
`;
},
});
export default App;
Here, we initialize our cache with an empty object as we do not have any default values to set (if you did, you'd pass them as the second argument as shown above).
Cache Value is Type-Agnostic
When setting a default value, be mindful of the data type that you use (e.g., an object, string, number, etc). Whenever you use the cache, you will want to match this type expectation. In other words, for an object-initialized cache, assume you're modifying an object; for a number-initialized cache, assume you're modifying a number.
API
cache(cache_name: string, default_value: any) => object
- cache_name string required
- The name of the cache.
- default_value string
- The default value for the cache. Accepts any data type.