hooks#useDebounce JavaScript Examples

The following examples show how to use hooks#useDebounce. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SearchUsers.jsx    From react-chatengine-demo with MIT License 4 votes vote down vote up
SearchUsers = ({ visible, closeFn }) => {
  let searchRef = useRef();

  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const debouncedSearchTerm = useDebounce(searchTerm, 500);

  // null -> not searching for results
  // [] -> No results
  // [...] -> Results
  const [searchResults, setSearchResults] = useState(null);

  useEffect(() => {
    if (visible && searchRef) {
      searchRef.focus();
    }
  }, [visible]);

  const {
    myChats,
    setMyChats,
    chatConfig,
    selectedChat,
    setSelectedChat,
  } = useChat();

  const selectUser = username => {
    addPerson(chatConfig, selectedChat.id, username, () => {
      const filteredChats = myChats.filter(c => c.id !== selectedChat.id);
      const updatedChat = {
        ...selectedChat,
        people: [...selectedChat.people, { person: { username } }],
      };

      setSelectedChat(updatedChat);
      setMyChats([...filteredChats, updatedChat]);
      closeFn();
    });
  };

  useEffect(() => {
    if (debouncedSearchTerm) {
      setLoading(true);
      getOtherPeople(chatConfig, selectedChat.id, (chatId, data) => {
        const userNames = Object.keys(data)
          .map(key => data[key].username)
          .filter(u =>
            u.toLowerCase().includes(debouncedSearchTerm.toLowerCase()),
          );
        setSearchResults(userNames.map(u => ({ title: u })));
        setLoading(false);
      });
    } else {
      setSearchResults(null);
    }
  }, [debouncedSearchTerm, chatConfig, selectedChat]);

  return (
    <div
      className="user-search"
      style={{ display: visible ? 'block' : 'none' }}
    >
      <Search
        fluid
        onBlur={closeFn}
        loading={loading}
        value={searchTerm}
        placeholder="Search For Users"
        open={!!searchResults && !loading}
        input={{ ref: r => (searchRef = r) }}
        onSearchChange={e => setSearchTerm(e.target.value)}
        results={searchResults}
        onResultSelect={(e, data) => {
          if (data.result?.title) {
            selectUser(data.result.title);
          }
        }}
      />
    </div>
  );
}
Example #2
Source File: index.js    From dstack-server with Apache License 2.0 4 votes vote down vote up
Card = memo(({
    data,
    className,
    type = 'grid',
    deleteCard,
    updateCard,
    filters,
    forwardedRef,
}: Props) => {
    const [title, setTitle] = useState(data.title);
    const {t} = useTranslation();
    const headId = get(data, 'head.id');
    const stackOwner = data.stack.split('/')[0];
    const [attachmentIndex, setAttachmentIndex] = useState(0);
    const [cardParams, setCardParams] = useState([]);

    useEffect(() => {
        const params = parseStackParams(get(data, 'head.attachments', []));

        if (params)
            setCardParams(Object.keys(params));

    }, [data]);

    useEffect(() => {
        findAttach();
    }, [filters]);

    const findAttach = () => {
        const attachments = get(data, 'head.attachments');
        const fields = Object.keys(filters).filter(f => cardParams.indexOf(f) >= 0);

        if (!attachments)
            return;

        if (fields.length) {
            attachments.some((attach, index) => {
                let valid = true;

                fields.forEach(key => {
                    if (!attach.params || !isEqual(attach.params[key], filters[key]))
                        valid = false;
                });

                if (valid)
                    setAttachmentIndex(index);

                return valid;
            });
        } else
            setAttachmentIndex(0);
    };

    const onUpdate = updateCard ? useDebounce(updateCard, []) : () => {};

    const onChangeTitle = event => {
        setTitle(event.target.value);
        onUpdate({title: event.target.value});
    };

    return (
        <div className={cx(css.card, `type-${type}`, className)} ref={forwardedRef}>
            <div className={css.inner}>
                <div className={css.head}>
                    <div className={cx(css.name, {readonly: !updateCard})}>
                        <div className={css.nameValue}>{title.length ? title : t('title')}</div>

                        <input
                            value={title}
                            type="text"
                            placeholder={t('title')}
                            onChange={onChangeTitle}
                            className={cx(css.nameEdit, {active: !title.length})}
                        />
                    </div>

                    <Tooltip
                        overlayContent={(
                            <Fragment>
                                <div>{t('updatedByName', {name: stackOwner})}</div>

                                {data.head && <div className={css.infoTime}>
                                    {moment(data.head.timestamp).format('D MMM YYYY')}
                                </div>}
                            </Fragment>
                        )}
                    >
                        <div className={css.info}>
                            <span className="mdi mdi-information-outline" />
                        </div>
                    </Tooltip>

                    <Button
                        className={cx(css.button, css.link)}
                        color="secondary"
                        Component={Link}
                        to={`/${data.stack}`}
                    >
                        <span className="mdi mdi-open-in-new" />
                    </Button>

                    {deleteCard && (
                        <Dropdown
                            className={css.dropdown}

                            items={[
                                {
                                    title: t('delete'),
                                    onClick: deleteCard,
                                },
                            ]}
                        >
                            <Button
                                className={css.button}
                                color="secondary"
                            >
                                <span className="mdi mdi-dots-horizontal" />
                            </Button>
                        </Dropdown>
                    )}

                    {updateCard && (
                        <Button
                            className={cx(css.button, css.move)}
                            color="secondary"
                        >
                            <span className="mdi mdi-cursor-move" />
                        </Button>
                    )}
                </div>

                {headId
                    ? <Attachment
                        className={css.attachment}
                        isList
                        withLoader
                        stack={data.stack}
                        frameId={headId}
                        id={attachmentIndex}
                    />

                    : <div className={css.emptyMessage}>{t('emptyDashboard')}</div>
                }
            </div>
        </div>
    );
})
Example #3
Source File: index.js    From dstack-server with Apache License 2.0 4 votes vote down vote up
Upload = ({stack, className, isShow, onClose, refresh, withButton}: Props) => {
    const {t} = useTranslation();
    const [isShowModal, setIsShowModal] = useState(false);
    const [uploading, setUploading] = useState(null);
    const [progress, setProgress] = useState(null);
    const [file, setFile] = useState(null);
    const isDidMount = useRef(true);
    const {user} = useParams();

    const {form, onChange, formErrors, checkValidForm} = useForm(
        {stack: stack || ''},
        {stack: ['required', 'no-spaces-stack', 'stack-name']}
    );

    const runValidation = useDebounce(checkValidForm);

    useEffect(() => {
        if (!isDidMount.current)
            runValidation();
        else
            isDidMount.current = false;
    }, [form.stack]);

    useEffect(() => {
        if (isShow !== undefined)
            setIsShowModal(isShow);
    }, [isShow]);

    const toggleModal = () => setIsShowModal(!isShowModal);

    const closeHandle = () => {
        if (onClose)
            onClose();
        else
            setIsShowModal(false);
    };

    const getErrorsText = fieldName => {
        if (formErrors[fieldName] && formErrors[fieldName].length)
            return [t(`formErrors.${formErrors[fieldName][0]}`)];
    };

    const submit = async () => {
        setProgress(null);
        setUploading(true);

        const params = {
            type: file.type,
            timestamp: Date.now(),
            id: uuid(),
            stack: `${user}/${form.stack}`,
            size: file.size,
        };

        if (file.size > MB)
            params.attachments = [{length: file.size}];
        else
            params.attachments = [{data: await fileToBaseTo64(file)}];

        try {
            const {data} = await api.post(config.STACK_PUSH, params);

            if (data.attachments && data.attachments.length) {
                const [attachment] = data.attachments;

                if (attachment['upload_url']) {
                    await axios.put(attachment['upload_url'], file, {
                        headers: {'Content-Type': 'application/octet-stream'},

                        onUploadProgress: progressEvent => {
                            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);

                            setProgress(percentCompleted);
                        },
                    });
                }
            }

            setUploading(false);
            closeHandle();

            if (refresh)
                refresh();
        } catch (e) {
            closeHandle();
        }
    };

    return (
        <Fragment>
            {withButton && <Tooltip
                overlayContent={t('uploadTooltip')}
            >
                <Button
                    className={cx(css.upload, className)}
                    size="small"
                    color="secondary"
                    onClick={toggleModal}
                >
                    {t('upload')}
                </Button>
            </Tooltip>}

            <Modal
                title={t('uploadFile')}
                isShow={isShowModal}
                size="small"
            >
                <div className={css.content}>
                    {!stack && (
                        <Fragment>
                            <div className={css.subtitle}>{t('theUploadedFileWouldBeSavedAsANewStack')}</div>

                            <TextField
                                size="middle"
                                className={css.field}
                                name="stack"
                                onChange={onChange}
                                value={form.value}
                                maxLength={30}
                                placeholder={`${t('stackName')}, ${t('noSpaces')}, ${t('maxSymbol', {count: 30})}`}
                                errors={getErrorsText('stack')}
                            />
                        </Fragment>
                    )}

                    {stack && file && (
                        <div className={css.subtitle}>{t('theUploadedFileWouldBeSavedAsANewRevisionOfTheStack')}</div>
                    )}

                    <FileDragnDrop
                        className={css.dragndrop}
                        formats={['.csv', '.png', '.svg', '.jpg']}
                        onChange={setFile}
                        loading={uploading}
                        progressPercent={progress}
                    />
                </div>

                <div className={css.buttons}>
                    <Button
                        className={css.button}
                        variant="contained"
                        color="primary"
                        disabled={!file || !form.stack.length || uploading}
                        onClick={submit}
                    >
                        {t('save')}
                    </Button>

                    <Button
                        onClick={closeHandle}
                        className={css.button}
                        variant="contained"
                        color="secondary"
                        disabled={uploading}
                    >
                        {t('cancel')}
                    </Button>
                </div>
            </Modal>
        </Fragment>
    );
}