2.0.0 • Published 5 years ago

use-dotnetify v2.0.0

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

use-dotnetify

use-dotnetify is a react library that provides hook access for dotnetify models.

Install

You must be using dotnetify.

  • npm install use-dotnetify or
  • yarn add use-dotnetify

Use

Using this library requires two parts. First is the Provider which uses react context to share the states and vms through the component hierarchy.

import React from "react"
import { DotNetifyProvider } from "use-dotnetify"
import HelloWorld from "./HelloWorld"

const App = () => (
  return (
    <DotnetifyProvider>
      <HelloWorld />
    </DotnetifyProvider>
  )
)

Now our HelloWorld component can access the view models and state provided by the server through the useDotNetify() hook. This will give us access to the state and vm objects generated by dotnetify.react.connect().

import React from "react"
import { useDotNetify } from "use-dotnetify"

const initialState = {
  FirstName: "",
  LastName: "",
  FullName: "",
}

const HelloWorld = () => {
  const [state, vm] = useDotNetify("HelloWorldVm", initialState)

  return (
    <div>
      <strong>{state.FullName}</strong>
    </div>
  )
}

Also provided is a simple hook that wraps state dispatches for single properties. This hook is useProperty() and accepts the model name and property name as parameters.

import React from "react"
import { useProperty } from "use-dotnetify"

const HelloWorld = () => {
  const [firstName, setFirstName, dispatchFirstName] = useProperty("HelloWorldVm", "FirstName")
  const [lastName, setLastName, dispatchLastName] = useProperty("HelloWorldVm", "LastName")

  return (
    <div>
      <input
        value={firstName}
        onChange={e => setFirstName(e.target.value)}
        onBlur={e => dispatchFirstName(e.target.value)}
      />
      <br />
      <input
        value={lastName}
        onChange={e => setLastName(e.target.value)}
        onBlur={e => dispatchLastName(e.target.value)}
      />
    </div>
  )
}

In the example above firstName and setFirstName function exactly as useState() would, only maintaining local state. The third returned value dispatchFirstName() will dispatch an update to the server that will update the HelloWorldVm.FirstName property with the new value.