How to use useQuery...?

Uber noob question here, I seem to have a misunderstanding of useQuery. Here is all im trying to do - use it to return an array from my database, console log the data. Here is my component, when it loads it doesn't log anything (because getAllCars.data hasn't resolved yet?), as if I need to await the data (what is the pattern for this in TRPC?). If I wasn't using TRPC, I would have the cars data set to a state so I can put the loop inside a useEffect with cars state as a dependancy, however I understand the TRPC patterns are different. Looking at the useQuery docs, the useQuery example doesn't help. The data just seems to be there? Anyway the solution is presumably. very simple, hoping someone can point me in the right direction
const AddPart: React.FC<AddPartProps> = () => {

const getAllCars = trpc.cars.getAll.useQuery();
const savePart = trpc.parts.createPart.useMutation();

useEffect(() => {
getAllCars.data?.forEach((car: ICar) => {
console.log(car.make)
});

}, []);


return (
<div>Test</div>
)
export default AddPart
const AddPart: React.FC<AddPartProps> = () => {

const getAllCars = trpc.cars.getAll.useQuery();
const savePart = trpc.parts.createPart.useMutation();

useEffect(() => {
getAllCars.data?.forEach((car: ICar) => {
console.log(car.make)
});

}, []);


return (
<div>Test</div>
)
export default AddPart
8 Replies
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
cornflour
cornflour2y ago
useQuery is a hook, not a function and it itself already returns the data
const AddPart: React.FC<AddPartProps> = () => {
// no need to define type here since it's already inferred from the return type of the backend function
const {data: cars} = trpc.cars.getAll.useQuery()
console.log(cars)
}
const AddPart: React.FC<AddPartProps> = () => {
// no need to define type here since it's already inferred from the return type of the backend function
const {data: cars} = trpc.cars.getAll.useQuery()
console.log(cars)
}
zezima
zezimaOP2y ago
Ugh, for some reason I thought only state could be used in a dep array. Like a thought, simple solution. Thankyou so much!
cornflour
cornflour2y ago
wait i misread the code fuck sorry yea just simple dep stuff
zezima
zezimaOP2y ago
No problem! Appreciate the response
cornflour
cornflour2y ago
i do wonder if the useEffect is necessary at all though
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
barry
barry2y ago
It's not data is state
Want results from more Discord servers?
Add your server