How can I await a query? tRPC
So how can I wait in my function until the query is done?
The problem is that in this code you have to call the search function over and over again until the data is fetched. How can I fix this?
btw. I'm calling the search function on enter/ on button click
const { data: findCitiesByNameData = [], status: findCitiesByNameStatus } =
api.search.findCitiesByName.useQuery({
name: searchValue.name,
});
const { data: findCityByIdData = [], status: findCityByIdStatus } =
api.search.findCityById.useQuery({
id: searchValue.id,
});
const { data: findCityByNameData = [], status: findCityByNameStatus } =
api.search.findCityByName.useQuery({
name: searchValue.name,
});
useEffect(() => {
if (searchValue.name === "") {
setResults([]);
return;
}
if (!findCitiesByNameData || findCitiesByNameStatus !== "success") return;
setResults(findCitiesByNameData);
}, [searchValue, findCitiesByNameData, findCitiesByNameStatus]);
const searchCity = () => {
let city: ICity | undefined = {
id: 0,
name: "",
country: "",
region: "",
coord: {
lon: 0,
lat: 0,
},
};
if (searchValue.id === -1) {
city = {
id: -1,
name: searchValue.name,
country: "",
region: "",
coord: {
lon: searchValue.coord.lon,
lat: searchValue.coord.lat,
},
};
} else {
if (searchValue.id !== 0 && searchValue.country !== "") {
if (!Array.isArray(findCityByIdData)) {
city = findCityByIdData.city;
} else {
toast.error(translationLocationSettings("city not found toast"));
return;
}
} else {
if (!Array.isArray(findCityByNameData)) {
city = findCityByNameData.city;
} else {
toast.error(translationLocationSettings("city not found toast"));
return;
}
}
}
const { data: findCitiesByNameData = [], status: findCitiesByNameStatus } =
api.search.findCitiesByName.useQuery({
name: searchValue.name,
});
const { data: findCityByIdData = [], status: findCityByIdStatus } =
api.search.findCityById.useQuery({
id: searchValue.id,
});
const { data: findCityByNameData = [], status: findCityByNameStatus } =
api.search.findCityByName.useQuery({
name: searchValue.name,
});
useEffect(() => {
if (searchValue.name === "") {
setResults([]);
return;
}
if (!findCitiesByNameData || findCitiesByNameStatus !== "success") return;
setResults(findCitiesByNameData);
}, [searchValue, findCitiesByNameData, findCitiesByNameStatus]);
const searchCity = () => {
let city: ICity | undefined = {
id: 0,
name: "",
country: "",
region: "",
coord: {
lon: 0,
lat: 0,
},
};
if (searchValue.id === -1) {
city = {
id: -1,
name: searchValue.name,
country: "",
region: "",
coord: {
lon: searchValue.coord.lon,
lat: searchValue.coord.lat,
},
};
} else {
if (searchValue.id !== 0 && searchValue.country !== "") {
if (!Array.isArray(findCityByIdData)) {
city = findCityByIdData.city;
} else {
toast.error(translationLocationSettings("city not found toast"));
return;
}
} else {
if (!Array.isArray(findCityByNameData)) {
city = findCityByNameData.city;
} else {
toast.error(translationLocationSettings("city not found toast"));
return;
}
}
}
0 Replies