Krisna
Krisna

Reputation: 3423

JavaScript input query string does not accept space tab but letter

I am using React-native typescript for my app . I have a TextInput, where user can pass some value(letter/letters) that value pass it to the Api's query string, and give search result. I have made one helper function which does not accept any space. It only accepts letter/letters.

I want to make helper function which take spaces but it will only trigger when there is letter/letter. It's really hard to explain. But I found Linkedin has this kind search filter, which logic I want implement in my app. But I don't know how to do that.

This is my code

import debounce from 'lodash/debounce';
import React, { useState, useRef } from 'react';

const SearchScreen = () => {
  const [searchText, setSearchText] = useState('');
  const [searchedText, setSearchedText] = useState('');
  const delayedSearch = useRef(
    debounce((text: string) => {
      _search(text);
    }, 400),
  ).current;

  const _clearSearch = () => {
    if (searchText.length === 0) {
      Keyboard.dismiss();
    }
    setSearchText('');
    setSearchedText('');
  };

  const _search = (text: string) => {
    setSearchedText(text);
  };

  const removeExtraSpace = (s: string) => s.trim().split(/ +/).join(' '); // this is my helper function which does not accept white space

  const _onSearchChange = (text: string) => {
    setSearchText(removeExtraSpace(text)); // in here I am using the helper function
    delayedSearch(removeExtraSpace(text)); // in here I am using the helper function
  };

  return (
    <Container>
      <SearchBar
        text={searchText}
        onClearText={_clearSearch}
        onChangeText={_onSearchChange}
      />

      <ProductSearchResult
        queryString={searchedText} // in here I a passing Search
      />
    </Container>
  );
};

export default SearchScreen;

Upvotes: 4

Views: 179

Answers (1)

Krisna
Krisna

Reputation: 3423

I made a mistake. My function works fine. But mistakenly I passed function to local state.

It should be like this:

  const _onSearchChange = (text: string) => {
    setSearchText(text);
    delayedSearch(removeExtraSpace(text));
  };

Upvotes: 1

Related Questions