1.0.2 • Published 1 year ago

@mattyreacts/debouncetextfield v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

DebounceTextField

Description

A React component based on @mui/material/TextField. The onChange callback is called only after the user has stopped modifying the text in the field for a defined period of time.

Installation

npm install @mattyreacts/debouncetextfield

Usage

See MUI TextField API for TextField properties

Extended Properties

NameTypeDefaultDescription
delaynumber500The delay on the debounce in milliseconds
onChange(value: string) => void-The callback to call after the delay timeout once editing has ceased
valuestring-The value of the field

Example

import * as React from "react";
import { useCallback, useState, useEffect } from "react";
import { Search } from "@mui/icons-material";
import DebounceTextField from "@mattyreacts/debouncetextfield";
import { Stack, Typography } from "@mui/material";

function DelaySearch(): React.JSX.Element {
    const [items, setItems] = useState<string[]>([]);
    const [search, setSearch] = useState<string>('');

    const handleSearchChange = useCallback((value: string) => {
        setSearch(value);
    }, []);

    useEffect((): void => {
        if(search.trim() === '')
            return;
        
        (async (): Promise<void> => {
            try {
                const res = await fetch(`/search?query=${search}`);
                const items = await res.json();
                setItems(items);
            } catch(err) {
                console.error(err);
            }
        })();
    }, [search]);

    return (
        <Stack direction="column">
            <DebounceTextField value={search} onChange={handleSearchChange} />
            {items.map((item: string, index: number) => (
                <Typography variant="body1" key={`item${index}`}>{item}</Topography>
            ))}
        </Stack>
    );
}
1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago