This article is about fixing Not setting react-select default value in Unform Unform
  • 22-Jan-2023
Lightrun Team
Author Lightrun Team
Share
This article is about fixing Not setting react-select default value in Unform Unform

Not setting react-select default value in Unform Unform

Lightrun Team
Lightrun Team
22-Jan-2023

Explanation of the problem

Issue Description:

A bug has been identified in the select field when passing a default value. The select field does not change when the default value is passed.

To Reproduce:

  1. Change the select and save the value on localStorage.
  2. Refresh the page and set the localStorage as form initialData.

Form field:

<SelectComponent
name="collections"
readOnly={submitting}
options={colecoes}
isLoading={colecoes.length === 0}
placeholder="Selecione a coleção..."
noOptionsMessage={() => 'Nenhuma coleção encontrada'}
onChange={handleChange}
/>

Select component:

  function getDefaultValue() {
    if (!defaultValue) return null;

    if (!multiple) {
      return options.find(option => option.id === defaultValue);
    }

    return options.filter(option => defaultValue.includes(option.id));
  }
  return (
    <Select
      name={fieldName}
      aria-label={fieldName}
      options={options}
      isMulti={multiple}
      defaultValue={getDefaultValue()}
      ref={refSelect}
      getOptionValue={option => option.id}
      getOptionLabel={option => option.title}
      className="enhanced-select"
      menuPlacement="auto"
      {...rest}
    />
  );

Troubleshooting with the Lightrun Developer Observability Platform

Getting a sense of what’s actually happening inside a live application is a frustrating experience, one that relies mostly on querying and observing whatever logs were written during development.
Lightrun is a Developer Observability Platform, allowing developers to add telemetry to live applications in real-time, on-demand, and right from the IDE.

  • Instantly add logs to, set metrics in, and take snapshots of live applications
  • Insights delivered straight to your IDE or CLI
  • Works where you do: dev, QA, staging, CI/CD, and production

Start for free today

Problem solution for Not setting react-select default value in Unform Unform

There are a few different ways to set the default value for a react-select component, depending on how the component is being used. Here are a few examples:

  • If you are using a controlled component, you can set the value prop to the desired default value. For example, if you have a state variable called selectedOption that holds the current value of the select, you can set the value prop to selectedOption:
<Select value={selectedOption} onChange={handleChange} options={options} />
  • If you are using an uncontrolled component, you can set the defaultValue prop to the desired default value. For example, if you want the default value to be the first option in your options array, you can set the defaultValue prop to options[0]:
<Select defaultValue={options[0]} options={options} />
  • If you are using a useState hook to manage the state of the select, you can set the initial state to the desired default value. For example, if you want the default value to be the first option in your options array, you can set the initial state to options[0]:
const [selectedOption, setSelectedOption] = useState(options[0]);

Please make sure that you are passing the correct props value to the react-select component. Please also make sure that the default value is included in the options array.

Other popular problems with Unform

Problem: Difficulty in handling multiple forms on the same page

When working with multiple forms on the same page, it can be difficult to manage the state of each form individually. This is because the state of each form is usually managed by a single useForm hook, which can make it difficult to distinguish between the different forms and their corresponding fields.

Solution:

One solution to this problem is to create a separate useForm hook for each form on the page. This way, the state of each form can be managed independently. Here is an example of how this can be done:

import { useForm } from 'react-hook-form'

function Form1() {
  const form1 = useForm()
  const { register, handleSubmit } = form1
  const onSubmit = data => console.log(data)

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="form1Field" ref={register} />
      <button type="submit">Submit</button>
    </form>
  )
}

function Form2() {
  const form2 = useForm()
  const { register, handleSubmit } = form2
  const onSubmit = data => console.log(data)

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="form2Field" ref={register} />
      <button type="submit">Submit</button>
    </form>
  )
}

Problem: Difficulty in handling Form Array fields

When working with forms that have fields that are repeated multiple times (such as a list of items), it can be difficult to manage the state of these fields. This is because the useForm hook does not provide a built-in way to handle arrays of fields.

Solution:

One solution to this problem is to use the Controller component provided by the react-hook-form library. This component can be used to control the state of an array of fields. Here is an example of how this can be done:

import { useForm, Controller } from 'react-hook-form'

function FormArray() {
  const form = useForm()
  const { register, handleSubmit } = form
  const onSubmit = data => console.log(data)

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
        as={<input />}
        name="items[]"
        control={form.control}
        defaultValue=""
      />
      <button type="submit">Submit</button>
    </form>
  )
}

Problem: Difficulty in handling async validation

When working with forms that have fields that need to be validated asynchronously (such as checking if an email is already in use), it can be difficult to handle this type of validation using the useForm hook.

Solution:

One solution to this problem is to use the watch function provided by the react-hook-form library. This function can be used to watch a specific field and trigger an async validation function when the field value changes. Here is an example of how this can be done:

import { useForm, useWatch } from 'react-hook-form'

function AsyncValidationForm() {
  const form = useForm()
  const { register, handleSubmit, errors, setError } = form
  
  const email = useWatch({ name: "email" });
  
  useEffect(() => {
    if (email) {
      checkEmailAvailability(email)
        .then((available) => {
          if (!available) {
            setError("email", "notUnique", "Email already in use");
          }
        });
    }
  }, [email, setError]);

  const onSubmit = data => console.log(data)

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="email" ref={register} />
      {errors.email && <p>{errors.email.message}</p>}
      <button type="submit">Submit</button>
    </form>
  )
}

Here, useWatch is used to watch the “email” field, whenever the value of the email field changes, it triggers the async function checkEmailAvailability. If the email is already in use the function setError(“email”, “notUnique”, “Email already in use”) is called and the error message will be displayed.

A brief introduction to Unform

Unform is a library for creating and managing forms in React applications. It is designed to simplify the process of creating and handling forms by providing a set of hooks and components that can be easily integrated into any React project.

One of the key features of Unform is its ability to handle form state management. It provides a set of hooks that can be used to handle the form state, such as the useField hook for handling individual form fields, and the useForm hook for handling the overall form state. These hooks allow developers to easily create forms that are fully controlled by React, which can help to improve the performance and scalability of the application. Additionally, Unform also provides a set of built-in validation rules that can be easily applied to form fields, as well as the ability to create custom validation rules.

Most popular use cases for Unform

  1. Unform can be used to create and manage forms in React applications. It provides a set of hooks and components that can be integrated into any React project, making it easy to create forms that are fully controlled by React. This can help to improve the performance and scalability of the application.
  2. Unform can handle form state management. It provides a set of hooks such as useField and useForm that can be used to handle individual form fields and the overall form state. This allows developers to easily create forms that are fully controlled by React, which can help to improve the performance and scalability of the application.
import { useField } from '@unform/core';

function Input({ name }) {
  const inputRef = useRef(null);
  const { fieldName, defaultValue = '', registerField } = useField(name);

  useEffect(() => {
    registerField({
      name: fieldName,
      ref: inputRef.current,
      path: 'value',
    });
  }, [fieldName, registerField]);

  return <input ref={inputRef} defaultValue={defaultValue} />;
}
  1. Unform also provides a set of built-in validation rules that can be easily applied to form fields. In addition, it also allows developers to create custom validation rules. This allows developers to easily validate form data, ensuring that it meets the necessary requirements before it is submitted.
Share

It’s Really not that Complicated.

You can actually understand what’s going on inside your live applications.

Try Lightrun’s Playground

Lets Talk!

Looking for more information about Lightrun and debugging?
We’d love to hear from you!
Drop us a line and we’ll get back to you shortly.

By clicking Submit I agree to Lightrun’s Terms of Use.
Processing will be done in accordance to Lightrun’s Privacy Policy.