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

lumbridge

v0.1.3

Published

Improved logic management for React apps.

Downloads

4

Readme

lumbridge

🏰 React application management made simple.

npm GitHub react

Main Features

  • Router: Simplified routing with built in route guards and hooks.
  • Persistor: Interact with data storage clients with ease.
  • Store: Quick to setup, modular local state management.

Installation

Using npm:

npm i --save lumbridge

Using yarn:

yarn add lumbridge

Import into a your app:

import { Store, Persistor, Router } from 'lumbridge';

const authStore = Store.create({
  // code...
});

Note: lumbridge components require no additional setup to start using in an existing React app.

Router

Structured and intuitive routing which allows you to easily create routes and manage the events related to those routes.

See detailed docs.

Considerations in design:

  • Avoid complexity by creating your routes using our simple JavaScript object configuration.
  • Route enter guards enable you to prevent a person accessing a route.
  • Route leave guards prevent a user from routing away from a component before the app is ready - such as when a form has not been saved.
  • Hooks allow you to monitor all changes in the route location.
  • Smart route prioritization makes sure the route which matches closest to the path is the route which is rendered.
  • Nested routes are easily created by embedding a router in a child component.

Example:

import { Router } from 'lumbridge';
import { HomePage, LoginPage, SignUpPage } from '../components/pages';

const authRouter = Router.create({
  routes: {
    home: {
      path: '/',
      exact: true,
      component: HomePage,
    },
    login: {
      path: '/login',
      component: LoginForm,
      enter: {
        before: () => userIsNotLoggedIn(),
      },
      leave: {
        before: () => saveDataBeforeLeaving(),
      },
    },
    signUp: {
      path: '/sign-up',
      component: SignUpPage,
      alias: ['hello', 'yellow'],
      enter: {
        before: () => userIsNotLoggedIn(),
      },
    },
  },
  change: {
    after: ({ match: { path } }) => {
      recordRouteForAnalytics(path);
    },
  },
});

Usage:

import { Link } from 'lumbridge';
import authRouter from '../routers/authRouter';

const DashboardRoutes = authRouter.compile();

const App = () => (
  <Dashboard>
    <Menu>
      <Link to="/">Home</Link>
      <Link to="/faq">FAQ</Link>
      <Link to="/about">About</Link>
    </Menu>
    <DashboardRoutes />
  </Dashboard>
);

Persistor

Easily interact with persistant data stores such as localStorage, GraphQL Servers, REST Servers, etc.

See detailed docs.

Considerations in design:

  • Built to be flexible so you can interface with any kind of data store.
  • Seperates concerns so that data requests are made seperately to how that data is displayed.
  • Scopes allow you to listen to multiple data requests with a the same callbacks - reducing a lot of code overhead.

Example:

import { Persistor } from 'lumbridge';
import { string, object } from 'yup';
import apolloClient from '../client';

const apolloPersistor = Persistor.create({
  methods: {
    /**
     * Wrapper around the apollo client query function.
     */
    query: {
      payload: {
        query: string().required(),
        variables: object(),
      },
      handler: ({ query, variables }) => {
        return apolloClient.query({ query, variables })
          .then(({ data }) => data);
      },
    },
    /**
     * Wrapper around the apollo client mutate function.
     */
    mutate: {
      payload: {
        query: string().required(),
        variables: object(),
      },
      handler: ({ query, variables }) => {
        return apolloClient.mutate({ mutation: query, variables })
          .then(({ data }) => data);
      },
    },
  },
});

Usage:

import React from 'react';
import { apolloPersistor } from '../persistors/apolloPersistor';

/**
 * Create an instance from the persistor, this will contain the common
 * request information (such as a GraphQL query).
 */
const meQueryInstance = apolloPersistor.instance({
  name: 'query',
  map: ({ ...args }) => ({
    ...args,
    query: `
      query($id: String) {
        me(id: $id) { name }
      }
    `,
  })
});

/**
 * Here is how you can use the instance in a React component using hooks.
 */
const MyProfile = ({ id }) => {
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState(null);
  
  /**
   * By passing everything in via an object, you get the following benefits:
   * 1. Unsubscribe from all functions on unwatch (avoid memory leaks)
   * 2. Get to pick and choose which functions to use where.
   * 3. Only fire run on mounting and unmounting of component.
   */
  useEffect(() => {
    const unwatch = meQueryInstance.watch({
      done: data => setData(data),
      catch: error => setError(error),
      status: loading => setLoading(loading),
    });
    return () => unwatch();
  }, []);

  /**
   * Executions are seperated from results so that it's
   * easy to refresh without extra code. This will fire when
   * the "id" changes.
   */
  useEffect(() => {
    meQueryInstance.execute({
      variables: { id },
    });
  }, [id]);

  return (
    <div>
      {data.me.name}
      {error && error.message}
      {loading}
    </div>
  );
};

Store

Share and validate data in multiple places around an app.

See detailed docs.

Considerations in design:

  • Access data in multiple locations throughout app without passing data through components.
  • Get awesome data validation by using Yup the third party validation library.
  • Is effective at managing form data.
  • Updates state using store.update({}) which is similar to how this.setState({}) works, only partially updating the store.
  • Reset the store by using store.reset() which will set the stores values back to their state.

Example:

import { Store } from 'lumbridge';
import { string, boolean, object } from 'yup';

const authStore = Store.create({
  schema: {
    token: {
      state: null,
    },
    userId: {
      state: null,
      validate: string(),
    },
    loggedIn: {
      state: false,
      validate: boolean().required(),
    },
    big: {
      state: null,
      validate: object({
        one: string().required(),
        two: string().required(),
      }),
    },
  },
  actions: {
    loginUser: ({ token, userId }) => ({
      token,
      userId,
      loggedIn: Boolean(token && userId),
    }),
  },
});

Usage:

import React from 'react';
import { authStore } from '../stores/authStore';

const HeaderBar = () => (
  <Menu>
    <Item onClick={() => authStore.reset()}>
      Logout
    </Item>
  </Menu>
);

You can also use stores with routes:

import { Router } from 'lumbridge';
import { authStore } from '../stores/authStore';

const authRouter = Router.create({
  routes: {
    home: {
      path: '/',
      exact: true,
      component: HomePage,
      enter: {
        before: () => authStore.state.loggedIn,
      },
    },
  },
});

You can also handle forms with stores:

import React from 'react';
import { authStore } from '../stores/authStore';
import FieldError from '../components/FieldError';

/**
 * Here is the same form but using React hooks.
 */
const LoginFormHooks = ({ onSubmit }) => {
  const [errors, setErrors] = useState({});
  const [state, setState] = useState({});
  
  useEffect(() => {
    const unwatch = authStore.watch({
      state: state => setState(state),
      errors: errors => setErrors(errors),
    });
    return () => unwatch();
  }, []); // fire only on mount and unmount (empty array)

  return (
    <form onSubmit={onSubmit}>
      <div>
        <input
          type="text"
          name="username"
          value={state.username}
          onChange={event => authStore.update({ username: event.target.value })}
        />
        {errors.username && <div>{errors.username}</div>}
      </div>
    </form>
  );
};

Packages