Hi I am facing a problem passing correct value to my api call.
if i were to send query = “were” i am only able to send “e” only the last word I type
This the input tag in which i ought to type search query
<input
type="text"
onChange={(e) => handleInputChange(e)}
placeholder="Search..."
className="input input-sm input-bordered input-secondary "
style={{
color: "white",
"::placeholder": { color: "white" },
}}
/>
and here is the logic for catching the value and sending an api call
const [search, setSearch] = useState({});
function handleInputChange(e) {
// Get the input value
const searchValue = e.target.value;
const val = { _q: searchValue };
setSearch(val);
}
const fetchSuggestions = async (query) => {
try {
// Replace this URL with your actual API endpoint for fetching suggestions
const response = await fetchProductsByFilters(query);
const data = response.data.products;
} catch (error) {
console.error("Error fetching suggestions:", error);
}
};
useEffect(() => {
fetchSuggestions(search);
console.log(search);
}, [search]);
the console.log in the above useEffect hook provide the correct query for e.g – {_q: ‘were’}, Consider my api calling
export function fetchProductsByFilters(
filter,
sort,
pagination,
admin,
search
) {
// filter = {"category":["smartphone","laptops"]}
// sort = {_sort:"price",_order="desc"}
// pagination = {_page:1,_limit=10}
// search = {_q:"searchQuery"}
let queryString = "";
for (let key in filter) {
const categoryValues = filter[key];
if (categoryValues.length) {
const lastCategoryValue = categoryValues[categoryValues.length - 1];
queryString += `${key}=${lastCategoryValue}&`;
}
}
for (let key in search) {
queryString += `${key}=${search[key]}&`;
}
for (let key in sort) {
queryString += `${key}=${sort[key]}&`;
}
for (let key in pagination) {
queryString += `${key}=${pagination[key]}&`;
}
if (admin) {
queryString += `admin=true`;
}
console.log(queryString);
return new Promise(async (resolve) => {
//TODO: we will not hard-code server URL here
console.log(queryString, 2);
const response = await fetch(
"http://localhost:8080/products?" + queryString
);
const data = await response.json();
const totalItems = await response.headers.get("X-Total-Count");
resolve({ data: { products: data, totalItems: +totalItems } });
});
}
In this the query string from the console.log(queryString) I get is _q=e , only the last letter, I type not the full word. Why is that can you help identify the root cause and modify the code