Skip to content
Snippets Groups Projects
SeniorSearch.tsx 2.27 KiB
Newer Older
/* eslint-disable react/jsx-props-no-spreading */
Defendi Alberto's avatar
Defendi Alberto committed
import React, { FC, useState } from 'react';
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';
import { getSeniorList } from 'api/getSeniorList';
import { ResponseProps } from 'api/ResponseProps';
Defendi Alberto's avatar
Defendi Alberto committed
import { Control, Controller } from 'react-hook-form';
import { InsertReservationProps } from './InsertReservationProps';
Defendi Alberto's avatar
Defendi Alberto committed
type SeniorSearchProps = {
  control: Control<InsertReservationProps>;
Defendi Alberto's avatar
Defendi Alberto committed
};

export const SeniorSearch: FC<SeniorSearchProps> = ({
  control,
}: SeniorSearchProps) => {
  const [value, setValue] = useState<ResponseProps | null>(null);
Defendi Alberto's avatar
Defendi Alberto committed
  const [seniors, setSeniors] = useState<ResponseProps[]>([]);
Defendi Alberto's avatar
Defendi Alberto committed
  const [query, setQuery] = useState<string>('');
Defendi Alberto's avatar
Defendi Alberto committed
  // FIX: Input closing when the data is changed.
  // The issue is caused by the stopped re-rendering of react hook form. Consider
  // attaching the value manually or to isolate this component.
  const handleChange = (newValue: string): void => {
Defendi Alberto's avatar
Defendi Alberto committed
    const MIN_SEARCH_LENGTH = 4;
    if (newValue.length >= MIN_SEARCH_LENGTH && value == null) {
      getSeniorList(newValue).then((list) => {
        if (list.length !== 0) {
Defendi Alberto's avatar
Defendi Alberto committed
          setSeniors(list);
Defendi Alberto's avatar
Defendi Alberto committed
        } else {
          setSeniors([]);
        }
      });
Defendi Alberto's avatar
Defendi Alberto committed
    <Controller
      control={control}
      name="senior"
      as={({ onChange }) => (
        <Autocomplete
          value={value}
          id="senior-searcher"
          onInputChange={(_, newValue) => handleChange(newValue)}
          onChange={(_, val) => {
            onChange(val?.id);
            setValue(val);
Defendi Alberto's avatar
Defendi Alberto committed
          options={seniors}
          getOptionSelected={(option, val) => option.id === val.id}
          getOptionLabel={(option) => option.user.lastName}
          renderOption={(option) => (
            <>
              {option.user.firstName} {option.user.lastName}{' '}
              {option.user.username} {option.memberCardNumber}
            </>
          )}
          renderInput={(params) => (
            <TextField
              {...params}
              label="Search a senior"
              variant="outlined"
              InputProps={{
                ...params.InputProps,
              }}
            />
          )}