I have a search bar that fetches movies from an API with the name of the movie [ on every keystroke].
I want to trim the extra spaces from both before and after the name, and only have one space between words..
[It should send the clean string to the query to be fetched]
example:
[(what i'm typing) ==> (what should be queried)]
" gran torino "
==> "gran torino"
" Pirates of the Caribbean "
==> "Pirates of the Caribbean"
code:
const fetchMovieList = async (query) => {
if (query !== '') {
setStatusFetch('loading');
try {
const res = await fetch(`[API]=${query}`);
const movieListFromApi = await res.json();
if (movieListFromApi.Response === 'True') {
setStatusFetch('resolved');
setStatusMovie('found');
setMovieList(movieListFromApi.Search);
} else {
setMovieList([]);
setStatusMovie('notFound');
}
setStatusFetch('idle');
} catch (error) {
setStatusFetch('rejected');
}
} else {
setMovieList([]);
setStatusMovie('');
}
};
const myDebouncedFunction = useCallback(debounce((query) => fetchMovieList(query), 1000), []);
const handleSearch = ({ target: { value: inputValue } }) => {
setSearchInputValue(inputValue);
myDebouncedFunction(inputValue);
};
<SearchBar
type='text'
name='query'
placeholder='Search movies...'
value={searchInputValue}
onChange={handleSearch}
icon='fa fa-search' />
NON WORKING SOLUTIONS
- .trim() doesn't allow me to use spaces between words..
- onBlur won't help either because i wont unfocus from the search bar. (Remove white spaces from both ends of a string inside a form - React)
- several regex expressions that i tried wouldn't allow spaces between words to (like .trim()) (https://stackoverflow.com/a/7636022/3186426)
How can i do it?? Im i missing something?
Thank you!