What is state-toggle?
The state-toggle npm package provides a simple utility to manage toggle states. It is particularly useful for managing binary states such as on/off, true/false, or active/inactive in applications. This package helps in creating a toggle function that can switch between two states and also provides a method to get the current state.
What are state-toggle's main functionalities?
Creating a toggle
This feature allows you to create a toggle between two states. The `toggle` function initializes the state and provides a method to switch between the initialized states. The example demonstrates initializing a toggle between 'on' and 'off' and toggling between these states.
const toggle = require('state-toggle');
const myToggle = toggle('on', 'off');
console.log(myToggle()); // 'on'
console.log(myToggle.toggle()); // 'off'
console.log(myToggle()); // 'off'
Getting the current state
This feature is used to retrieve the current state of the toggle. The example shows how to initialize a toggle and retrieve the state before and after toggling.
const toggle = require('state-toggle');
const myToggle = toggle('active', 'inactive');
console.log(myToggle()); // 'active'
myToggle.toggle();
console.log(myToggle()); // 'inactive'
Other packages similar to state-toggle
switchery
Switchery is another package that provides functionality for creating switch controls that can toggle between two states. Unlike state-toggle, which is more focused on state management, Switchery also integrates visual components for web interfaces.
state-toggle
Enter/exit a state.
Installation
npm:
npm install state-toggle
Usage
var toggle = require('state-toggle')
var ctx = {on: false}
var enter = toggle('on', ctx.on, ctx)
var exit
exit = enter()
console.log(ctx.on)
exit()
console.log(ctx.on)
API
toggle(key, initial[, ctx])
Create a toggle, which when entering toggles key
on ctx
(or this
,
if ctx
is not given) to !initial
, and when exiting, sets key
on
the context back to the value it had before entering.
Returns
Function
— enter
.
enter()
Enter the state.
Context
If no ctx
was given to toggle
, the context object (this
) of enter()
is used to toggle.
Returns
Function
— exit
.
exit()
Exit the state, reverting key
to the value it had before entering.
License
MIT © Titus Wormer