Home > Software design >  Using "use-places-autocomplete" hook with Material-UI's Autocomplete?
Using "use-places-autocomplete" hook with Material-UI's Autocomplete?

Time:09-29

I'm trying to use this hook along with Material-UI's Autocomplete component, but am not having much success. Does anyone have an example of this scenario?

I receive a TS error for the value prop, stating

Type 'string' is not assignable to type 'AutocompletePrediction | null | undefined'.

The main issue though is that when I type into the input, results aren't being displayed for some reason, and neither the handleSelect nor the handleInput methods are being triggered.

Here's what I have so far:

import { useEffect, useRef, useState } from 'react';
import {
  ClickAwayListener,
  Grid,
  TextField,
  Typography,
} from '@material-ui/core';
import LocationOnIcon from '@material-ui/icons/LocationOn';
import parse from 'autosuggest-highlight/parse';
import Autocomplete from '@material-ui/lab/Autocomplete';
import usePlacesAutocomplete, {
  getGeocode,
  getLatLng,
} from 'use-places-autocomplete';

interface Props {
  onSelect: (value: string) => void;
}

const EditLocation: React.FC<Props> = ({ onSelect }) => {
  const {
    ready,
    value,
    suggestions: { status, data },
    setValue,
    clearSuggestions,
  } = usePlacesAutocomplete({
    debounce: 300,
  });

  const handleInput = e => {
    setValue(e.target.value);
  };

  const handleSelect =
    ({ description }: { description: string }) =>
    () => {
      console.log({ description });
      // When user selects a place, we can replace the keyword without request data from API
      // by setting the second parameter to "false"
      setValue(description, false);
      clearSuggestions();

      // Get latitude and longitude via utility functions
      getGeocode({ address: description })
        .then(results => getLatLng(results[0]))
        .then(({ lat, lng }) => {
          console.log('           
  • Related