GithubHelp home page GithubHelp logo

Comments (10)

avkonst avatar avkonst commented on August 22, 2024

They not mutually exclusive. You can use both. I do not have life example, but here is the snippet:

const state = useStateLink({ name: 'Josh' }, link => {
    // enable the plugin
    link.with(Validation)
    // add validation rules
    Validation(link.nested.name).validate(name => name !== "", 'Name should not be empty');

    // transform the result
    return {
         getName: () => l.nested.name.get(),
         setName: (v: string) => l.nested.name.set(v),
         isStateValid: () => Validation(link).valid(),
         isNameValid: () => Validation(link.nested.name).valid(), 
    }
})

// ... use the state now:
return <p>Name: ${state.getName()}. Is name valid?: ${state.isNameValid()}</p>

from hookstate.

avkonst avatar avkonst commented on August 22, 2024

Does it answer your question?

from hookstate.

chasm avatar chasm commented on August 22, 2024

Yep, with slight modifications (you must have typed this in a hurry):

const state = useStateLink({ name: 'Josh' }, link => {
    // enable the plugin
    link.with(Validation)

    // add validation rules
    Validation(link.nested.name).validate(name => name !== "", 'Name should not be empty');

    // transform the result
    return {
         getName: () => link.nested.name.get(),
         setName: (v: string) => link.nested.name.set(v),
         isStateValid: () => Validation(link).valid(),
         isNameValid: () => Validation(link.nested.name).valid(), 
    }
})

// ... use the state now:
return <p>Name: {state.getName()}. Is name valid?: {state.isNameValid()}</p>

Thanks! Works well.

from hookstate.

avkonst avatar avkonst commented on August 22, 2024

You can also invoke Validation(link.nested.name).validate(name => name !== "", 'Name should not be empty'); by a trigger from a user, but not when transform is called. For example:

    return {
         getName: () => link.nested.name.get(),
         setName: (v: string) => link.nested.name.set(v),
         validateName: (minLength: number) => Validation(link.nested.name).validate(name => name.length >= minLength, 'Name should not be short');
         isStateValid: () => Validation(link).valid(),
         isNameValid: () => Validation(link.nested.name).valid(), 
    }

and use validateName(...) before render return.

from hookstate.

avkonst avatar avkonst commented on August 22, 2024

PS: If you like it, please, consider to spread few words about the library to help the project to grow. And hello from New Zealand. I am from NZ too :)

from hookstate.

chasm avatar chasm commented on August 22, 2024

Will do. This is on a project for a startup, but I will probably do a presentation at a local meetup in Wellington in the near future to talk about this. Will let you know.

from hookstate.

avkonst avatar avkonst commented on August 22, 2024

Let me know when you do talk. I might join.

from hookstate.

chasm avatar chasm commented on August 22, 2024

That would be great. Are you in Wellington?

Here is what I'm doing with hookstate:

import { createStateLink, useStateLink } from '@hookstate/core'
import { Validation } from '@hookstate/validation'
import { Initial } from '@hookstate/initial'
import { Touched } from '@hookstate/touched'

export default function useFormState(initialState = {}, validators = []) {
  const state = createStateLink({}, link => {
    link
      .with(Initial)
      .with(Touched)
      .with(Validation)

    validators.forEach(v =>
      Validation(link.nested[v.name]).validate(v.validator, v.message),
    )

    return Object.keys(initialState).reduce(
      (acc, key) =>
        Object.defineProperty(acc, key, {
          get: function() {
            return link.nested[key].get()
          },
          set: function(val) {
            link.nested[key].set(val)
          },
        }),
      {
        isDirty: name =>
          name
            ? Initial(link.nested[name]).modified()
            : Initial(link).modified(),
        isTouched: name =>
          name ? Touched(link.nested[name]).touched() : Touched(link).touched(),
        isValid: name =>
          name
            ? Validation(link.nested[name]).valid()
            : Validation(link).valid(),
        isShallowValid: () => Validation(link).validShallow(),
        errors: name =>
          name
            ? Validation(link.nested[name]).errors()
            : Validation(link).errors(),
        firstError: name =>
          name
            ? Validation(link.nested[name]).firstError()
            : Validation(link).firstError(),
      },
    )
  })

  return useStateLink(state)
}

Then:

import React from 'react'
import useFormState from '@state/useFormState'

import { EMAIL_CHECK, PASSWORD_CHECK } from '@utils/constants'

const ExampleComponent = () => {
  const formState = useFormState(
    {
      email: '[email protected]',
      password: 'xyz123ABC!',
    },
    [
      {
        name: 'email',
        validator: (email = '') => EMAIL_CHECK.test(email),
        message: 'Email must be valid.',
      },
      {
        name: 'email',
        validator: (email = '') => email.length > 5,
        message: 'Email must be at least 5 characters long.',
      },
      {
        name: 'password',
        validator: (password = '') => PASSWORD_CHECK.test(password),
        message: 'Password must be valid.',
      },
    ],
  )

  return (
    <div style={{ margin: '0 100px 300px' }}>
      <p>Email: {formState.email}.</p>
      <p>Valid? {formState.isValid('email').toString()}.</p>
      <p>All valid? {formState.isValid().toString()}.</p>
      <pre>Errors? {JSON.stringify(formState.errors(), null, 2)}</pre>
      <pre>
        Email errors? {JSON.stringify(formState.errors('email'), null, 2)}
      </pre>
      <pre>
        Password errors? {JSON.stringify(formState.errors('password'), null, 2)}
      </pre>
      <p>First error? {JSON.stringify(formState.firstError(), null, 2)}</p>
      <p>
        First email error?{' '}
        {JSON.stringify(formState.firstError('email'), null, 2)}
      </p>
      <p>
        First password error?{' '}
        {JSON.stringify(formState.firstError('password'), null, 2)}
      </p>
    </div>
  )
}

export default ExampleComponent

Of course, eventually the form schema will be imported and injected into useFormState. I may also generate the form itself from the schema. We'll see.

from hookstate.

avkonst avatar avkonst commented on August 22, 2024

you can improve your useFormState by replacing const state = createStateLink by return useStateLink and dropping the last line. It will work the same way as useStateLink has got transform argument too. This way, each new rerender will avoid creating the state (might be not very important for your app).

from hookstate.

chasm avatar chasm commented on August 22, 2024

Thanks! Good to know.

from hookstate.

Related Issues (20)

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.