I have a search bar in my React JS application that gets an input and search for it in a table:
const [search, setSearch] = useState('');
const [users, setUsers] = useState([]);
useEffect(async () => {
const response = await getUsers(search);
setUsers(response.data.users);
}, [search]);
.
.
.
<input type='text' className='my-3 py-2 pl-3 pr-10 text-sm' placeholder='search term..' onChange={(e) => setSearch(e.target.value)} value={search} />
It works fine. Now I want to make it possible that when my string contains a special character, replace that character with another one and search for the new term. For example, if my string is hello
, I want to change h
to m
and search for mello
. I changed my code to this:
useEffect(async () => {
if (search.indexOf('h') > -1)
{
alert('Found');
search = search.replace("h", "m");
}
const response = await getUsers(search);
setUsers(response.data.users);
}, [search]);
Now when input string contains h
, I receive an alert but the searching process is not working correctly (it does not search for anything). What can I do?
CodePudding user response:
The logic you implemented only needs a small change because you are trying to set the value into the search variable but this only can be updated using the setter instead of setting the value directly. If you are trying to only override the character before calling getUsers this can help you to fix your code.
useEffect(async () => {
let searchValue = search.indexOf('h') > -1? search.replace("h", "m") : search;
const response = await getUsers(searchValue);
setUsers(response.data.users);
}, [search]);