Code Monkey home page Code Monkey logo

react-use-url-state's Introduction

react-use-url-state

npm npm type definitions npm npm bundle size Known Vulnerabilities

Use URL params to store a state in React.

  • Handle numbers, dates, booleans, and arrays.
  • Have a type-safety with Zod
  • CJS and ESM support
  • 0 dependencies

https://example.com/?text=query&number=10&date=2023-11-29T13%3A52%3A50.230Z

<=>

{ text: 'query', number: 10, date: new Date('2023-11-29T13:52:50.230Z') }

Installation

npm i react-use-url-state zod

Documentation

๐Ÿ“Documentation and examples

Usage

๐Ÿ’ฌ It's important to use .coerce on your Zod schema to ensure that the values are parsed correctly from the URL.

function MyComponent() {
  const { data, setState, setValue, setValues, isError, error } = useUrlState(
    z.object({
      name: z.string(),
      age: z.coerce.number(),
      birthDate: z.coerce.date().optional(),
    }),
  );

  return <div>
    <Button
      onClick={() => {
        setState({ name: 'test', age: 10, birthDate: new Date() });
      }}
    >
      Set state
    </Button>

    <Button
      onClick={() => {
        setValue('age', data.age + 1);
      }}
    >
      Increment age
    </Button>

    <pre>{JSON.stringify(data, null, 2)}</pre>
  </div>
}

react-use-url-state's People

Contributors

snyk-bot avatar wanjas avatar

Stargazers

 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.