Comments (10)
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.
Does it answer your question?
from hookstate.
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.
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.
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.
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.
Let me know when you do talk. I might join.
from hookstate.
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.
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.
Thanks! Good to know.
from hookstate.
Related Issues (20)
- Any showcase how to work with Immutables? HOT 2
- Resource leak with `useHookstate` HOT 2
- Is this lib still being updated? HOT 3
- Request: throw error when trying to assign nested state to a Proxy object HOT 2
- Migration from 3 to 4 HOT 4
- Localstored - optional initializer HOT 1
- https://hookstate.js.org/docs/exceptions/#hookstate-106 is killing me HOT 1
- What is the meaning of `E` in State<S, E>? HOT 1
- Injecting React-Router-dom instance into the store HOT 1
- one of my favourite projects really HOT 4
- More than 5 extensions loading HOT 2
- Creating a global object using hookstate, but unable to find the property when using it. HOT 2
- How to handle file objects in v4? HOT 1
- Isolating global states between tests HOT 4
- state.attach is not a function
- Combine extensions HOT 3
- Nextjs: localstorage is not defined HOT 6
- having problem with getting rid of proxy HOT 2
- Broadcasted state extension not working HOT 2
- 106 EXCEPTION 'Cannot Convert Undefined Value to Object' Error when setting and getting global store state in two seperate components HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from hookstate.