useFieldValue()

Allows you to get and set values for any field.

This hook is commonly used when showing or hiding fields based on their value.

Props

Props in

Props out

When to use?

At the moment, OneForm doesn't allow you to render or not render a field based on its value. For now, this hook is required for those use cases.

You can even use it to display a list of notifications which disappear after 5 seconds:

import { useFieldValue } from '@oneform/react';
import {
  memo,
  useEffect,
} from 'react'

const NotificationsExample = () => {
  const {
    setValue,
    value = [],
  } = (
    useFieldValue({
      // `name` doesn't exist on an `input`. It's made for this component.
      name: 'notifications',
    })
  )
  
  useEffect(
    () => {
      if (value.length === 0) {
        return
      }
      
      const timeoutId = (
        setTimeout(
          () => {
            setValue(
              []
            )
          },
          5000,
        )
      )
      
      return () => {
        clearTimeout(
          timeoutId
        )
      }
    },
    [
      setValue,
      value,
    ],
  )

  return (
    <div>
      <h2>
        Notifications
      </h2>
    
      <ul>
        {
          value
          .map((
            notification,
          ) => (
            <li>
              {notification}
            </li>
          ))
        }
      </ul>
    </div>
  )
}

const MemoizedNotificationsExample = memo(NotificationsExample)

export default MemoizedNotificationsExample

Last updated