npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@myopia/optics

v1.0.2

Published

A state management library based on optics

Downloads

92

Readme

optics

optics is a state management library for typescript apps based on monocle-ts. It currently implements a single reducer and action creator, ready to be hooked in a standard redux setup.

install

npm install @myopia/optics

setup

In your store setup, just hook up the reducer provided. It's the only one you'll need.

You can either use the reducer and dispatch an action to set the initial state:

import {createStore, applyMiddleware} from 'redux'
import {initialState, State} from './state.ts'
import {reducer, OpticsAction, updateState} from '@myopia/optics'

export const store =
    createStore<State, OpticsAction<State>, void, void>(
        reducer,
        applyMiddleware(...)
    )

store.dispatch(
  updateState<State>(_ => initialState)
)

Or use createReducer and pass your initial state

import {createStore, applyMiddleware} from 'redux'
import {initialState, State} from './state.ts'
import {createReducer, OpticsAction, updateState} from '@myopia/optics'

export const store =
    createStore<State, OpticsAction<State>, void, void>(
        createReducer(initialState),
        applyMidleware(...)
    )

Your side effects layer is now ready to dispatch update actions:


function* save(action) {
    const result = yield call(api, {data: action.payload})
    if (result.isSuccess)
        yield put(updateState(...))
}

usage

Feel free to look at the example todos app, particularly the following files:

todo actions

visibility actions

lenses

What arguments do I pass to my update state?

Any lens composed from your state root

// in your lenses

const getAuthentication = Lens.fromProp<State>()('authentication')
const getCurrentUser = Lens.fromProp<Authentication>()('currentUser')
const selectCurrentUser = getAuthentication.compose(getCurrentUser)

// in your saga

yield put(updateState(
    selectCurrentUser.set(newValue)
))

// you can also do multiple updates

yield put(updateState([
    selectName.set('New Name'),
    selectEmail.set('[email protected]'),
    selectAge.set(55),
]))

image

Optics, more specifically lenses give you access to all getters and setters for every property of your state tree. Lenses are also composable so you can modify a deeply nested object property by passing a reference to the full object, and a function to update the specific property. All lenses operations are immutable.

you're tired of writing reducers and selectors

As an example, let's say you want to retrieve some nested property from your state and show it in a view. Then you want to update it somehow. Here's a side by side comparison between the standard redux abstractions like selectors and reducers, and optics using redux-saga :

Standard | Optics :---------------------:|:-------------------------: |

Note that we don't have to write tests for the reducers or selectors on the second case, because there are no reducers, and no selectors, just lenses. Another benefit we gained for free here is that we remove all the possible "logic" from our reducers. Some random dev wouldn't even be able to

(state, action) =>
    if (state.shouldDoLogicInReducer) ? "no" : "nope"

and make your reducer really hard to understand. Optics also makes you think more generically about your update functions, since they are the only thing you should test. If you plan on updating a collection with a new value, write a generic collection append function, test it once and never again think about writing tests again.

but wait, I still have to write all those lenses...

well, not really.

The optics generator should be able to generate all lenses from basic typescript definitions, even across multiple files. It is under active development.

dependencies

You'll want to get monocle-ts and fp-ts.

optics also extend monocle-ts and introduces the concept of projections, which is a peer of this library.

optics shouldn't actually depend on redux at all, but we do export everything as a reducer and action creator to make use of the great devtools redux has.

documentation

If you're looking for more information about optics in typescript, the monocle-ts website is a good start. More information will be added to the optics library as needed.