VoliJS / NestedLink

Callback-free React forms with painless validation.
MIT License
194 stars 25 forks source link

LinkAll with React.useState hook #40

Closed avkonst closed 5 years ago

avkonst commented 5 years ago

Thanks for the great library!

I typically link all state by using inheritance from LinkedComponent. It is a way based on class inheritance. It works. However, I have found that React Hooks from (16.8) simplify code a lot but they require components to be functions, not classes. I would like to use something similar to this.linkAll() but within functions where I could combine the links with React.useState(). I am trying to achieve something similar to the following. How should I do it properly?

const MyComponent = (props: { data: { field1: string }}) => {
    const [state, setState] = React.useState(props.data);
    const links = AnalogyOfLinkAll(state, setState); // <----- How can I do this?
    return <input value={links.field1.value} onChange={(v) => links.field1.set(v)} />;
};
gaperton commented 5 years ago

Done in 1.6.x. Not exactly like that, but I'd say it looks even better the way I did it. Oh, it so damn good that I even started to like hooks. Just

const data1 = useLink( "" ),
      data2 = useLink( 2 );

https://medium.com/@gaperton/react-hooks-and-two-way-data-binding-dd4210f0ed94

It seems that we don't need linkAll with hooks at all. Also, check the examples/todomvc. I updated it to use hooks. Much, much better than before.

avkonst commented 5 years ago

Alternatively, you can use valuelink from react-use-state-x, which I extracted today to opensource. Please, consider to reference it in your project as an alternative. I refer to yours one. Thanks.