Son
Son
TtRPC
Created by Son on 5/14/2023 in #❓-help
Is this blog correct? Trpc and next.js 13.4, App directory
I working on integrating with TRPC with the App directory and was given a solution but i'm not sure if the author or myself have the right understanding of how server components work with client components. The scenario: By adding the ‘use client’ directive in the route app layout file which the author suggests, wouldn't that mean all children components would become client-side components, so we would loose the benefits of server components? I was referring to this line in the blog specifically “This can be achieved by wrapping the provider around the {children} node in the src/app/layout.tsx file, which is the main entry point of the application.“ So this would mean next would render all children components as client components, as the provider would have to be at the root of the tree. Meaning are whole app would basically be a client side rendered app? https://codevoweb.com/setup-trpc-server-and-client-in-nextjs-13-app-directory/#comment-1755 I got a response from the blog author “I understand your point now. It's important to note that Client Components can be rendered within Server Components as long as the "use client"; pragma is included in the files that have the Client Components. Wrapping the tRPC provider around the prop of the root layout component allows Next.js to make the hooks and components from the tRPC library available to all Client Components that are descendants of the root layout component. It's important to remember that even though you've wrapped a provider component that has the "use client"; pragma around the prop of the root layout component, Next.js will still render all components inside the app directory as Server Components. This means that the only way all your components will be Client Components is if you include the "use client"; directive at the beginning of the files that contain them. I hope this explanation clarifies things for you. If you have any further questions, please don't hesitate to ask.”
3 replies
TtRPC
Created by Son on 3/21/2023 in #❓-help
How to call useQuery with params inside JSX
How can i achieve this? Thanks
export function MemberQueryList({ list }: Props) {

function checkIsOwner(housingAssociationId: string, memberId: string) {
const isOwner = trpc.housingAssociation.checkIfOwner.useQuery({
housingAssociationId,
memberId,
});

return isOwner.data?.ok ?? false;
}
const navigate = useNavigate();
const userId = getSubFromLocalStorage() ?? "";
return (
<div>
{list.map((housingAssociation: listData) => {
const isOwner = checkIsOwner(housingAssociation.id, housingAssociation.userId);
return (
<BoardCard
key={housingAssociation.id}
onClick={() => {
navigate(
`/housing_associations/association?name=${housingAssociation.name}&id=${housingAssociation.id}`
);
}}
state={housingAssociation}
isOwner={isOwner}
/>
);
})}
</div>
);
}
export function MemberQueryList({ list }: Props) {

function checkIsOwner(housingAssociationId: string, memberId: string) {
const isOwner = trpc.housingAssociation.checkIfOwner.useQuery({
housingAssociationId,
memberId,
});

return isOwner.data?.ok ?? false;
}
const navigate = useNavigate();
const userId = getSubFromLocalStorage() ?? "";
return (
<div>
{list.map((housingAssociation: listData) => {
const isOwner = checkIsOwner(housingAssociation.id, housingAssociation.userId);
return (
<BoardCard
key={housingAssociation.id}
onClick={() => {
navigate(
`/housing_associations/association?name=${housingAssociation.name}&id=${housingAssociation.id}`
);
}}
state={housingAssociation}
isOwner={isOwner}
/>
);
})}
</div>
);
}
6 replies
TtRPC
Created by Son on 1/31/2023 in #❓-help
i have an infinite loop within my hook but apps works as expected.
when i console log inside this hook, it repeats non-stop every few seconds, but my app is working as expected there is no infinite loop per say. i'm really confused with this one.
import zustand from ...

export function useGetTickets(tenantId?: any) {
const setTickets = useTicketStore((state) => state.setTickets);
const isApiError = useTicketStore((state) => state.isApiError);
const setIsApiError = useTicketStore((state) => state.setIsApiError);

const { isLoading, isError, data } =
trpc.getTicketsWithPhotos.getAll.useQuery(undefined, {
onSuccess: (data) => {
console.log("data", data);
setIsApiError(false);
setTickets(data.tickets);
},
onError: (e) => {
showToastCustomError(
"Sever Error",
"We cannot connect to our servers, please try again later or contact support",
8000
);
setIsApiError(true);
return console.error(e.message);
},
});

return { data, isLoading, isApiError };
}
import zustand from ...

export function useGetTickets(tenantId?: any) {
const setTickets = useTicketStore((state) => state.setTickets);
const isApiError = useTicketStore((state) => state.isApiError);
const setIsApiError = useTicketStore((state) => state.setIsApiError);

const { isLoading, isError, data } =
trpc.getTicketsWithPhotos.getAll.useQuery(undefined, {
onSuccess: (data) => {
console.log("data", data);
setIsApiError(false);
setTickets(data.tickets);
},
onError: (e) => {
showToastCustomError(
"Sever Error",
"We cannot connect to our servers, please try again later or contact support",
8000
);
setIsApiError(true);
return console.error(e.message);
},
});

return { data, isLoading, isApiError };
}
6 replies
TtRPC
Created by Son on 12/11/2022 in #❓-help
trpc hook pattern. This works, but I’m not convinced…
I want to call my route when a button is clicked and have access to isLoading, onError etc… I have implemented a pattern using ‘’refetch()’’ but it doesn’t feel ‘correct’ is there a better way of doing this. I will also create a custom hook out of it. ‘’’js const { refetch } = trpc.authDomain.signIn.useQuery( { email: userEmail }, { enabled: false, onError: (e: any) => { console.log('there was an error with the endpoint'); }, } ); async function isEmailVerified() { const response = await refetch(); const verification = response.data; // i want to access isLoading directly without writing many lines of new code which i would have to with this current approach if (verification?.status === 'tryAgain') { console.log('email not verified'); setHasInitiatedSignIn(true); } if (verification?.status === 'ok') { console.log('user can now verify code sent to their email address'); setHasInitiatedSignIn(true); } } Return <button onClick={isEmailVerified}/> ‘’’
7 replies
TtRPC
Created by Son on 12/7/2022 in #❓-help
correct way to call TRPC inside a function
13 replies
TtRPC
Created by Son on 11/24/2022 in #❓-help
Delay IsLoading....
i'm trying to delay a loading spinner from appearing if the api takes less than 200ms to get the data. I've tried a number of implementations and failed, can anyone help?
const { isLoading, isError, data } = trpc.ticketDomain.getByTicketId.useQuery(
{
ticketId: selectedTicket!.id,
}
);

if (isLoading) {
// details section should not render if isloading has been true for 200ms or less and if 'data' is not available

// load data as soon as its available and render the details section

// if fetching takes longer than 200ms, show loading spinner
return (

<LoadingSpinner />;

);
}
const { isLoading, isError, data } = trpc.ticketDomain.getByTicketId.useQuery(
{
ticketId: selectedTicket!.id,
}
);

if (isLoading) {
// details section should not render if isloading has been true for 200ms or less and if 'data' is not available

// load data as soon as its available and render the details section

// if fetching takes longer than 200ms, show loading spinner
return (

<LoadingSpinner />;

);
}
6 replies
TtRPC
Created by Son on 11/21/2022 in #❓-help
TRPC Testing Wrapper - Unit Testing components that contain a query (Not testing the query it self)
14 replies
TtRPC
Created by Son on 11/18/2022 in #❓-help
testing a trpc hook
i'm brand new to testing and need some help with writing a test for a hook that is returning an object. im stuck with the error messages. i'm using trpc and react query
export function useGetTenantTickets() {
const setTickets = useTenantStore((state) => state.setTickets);
const { isLoading, isError } = trpc.ticketDomain.getByTenantId.useQuery(
undefined,
{
onSuccess: (data) => {
setTickets(data);
},
}
);

return { isLoading, isError };
}
export function useGetTenantTickets() {
const setTickets = useTenantStore((state) => state.setTickets);
const { isLoading, isError } = trpc.ticketDomain.getByTenantId.useQuery(
undefined,
{
onSuccess: (data) => {
setTickets(data);
},
}
);

return { isLoading, isError };
}
my test
it('should return an object', async () => {
const tickets = renderer.create(<TenantTicketsScreen />);
const result = useGetTenantTickets();
const expected = {
isError: expect.any(Boolean),
isLoading: expect.any(Boolean),
};

expect(result).toEqual(expected);
});
it('should return an object', async () => {
const tickets = renderer.create(<TenantTicketsScreen />);
const result = useGetTenantTickets();
const expected = {
isError: expect.any(Boolean),
isLoading: expect.any(Boolean),
};

expect(result).toEqual(expected);
});
4 replies
TtRPC
Created by Son on 11/11/2022 in #❓-help
Object keeps getting overwritten
I feel like i'm missing something fundamental here. when I add a new entry into object b it resets to an empty object upon a subsequent request. Can anyone help?
addNewTicket: ticketsDomainProcedure
.input(
z.object({
id: z.string(),
title: z.string(),
description: z.string(),
type: z.string(),
status: z.string(),
})
)
.mutation(async (req) => {
const b = {};

console.log('original', b);

const tenantId = '908e2d94-aef7-4ba6-a1a3-2ccec65a1d97';

const updatedState = {
...b,
[req.input.id]: {
id: req.input.id,
tenantId: tenantId,
title: req.input.title,
description: req.input.description,
type: req.input.type,
status: req.input.status,
},
};

console.log('NEW STATE', updatedState);

return updatedState;
}),
});
addNewTicket: ticketsDomainProcedure
.input(
z.object({
id: z.string(),
title: z.string(),
description: z.string(),
type: z.string(),
status: z.string(),
})
)
.mutation(async (req) => {
const b = {};

console.log('original', b);

const tenantId = '908e2d94-aef7-4ba6-a1a3-2ccec65a1d97';

const updatedState = {
...b,
[req.input.id]: {
id: req.input.id,
tenantId: tenantId,
title: req.input.title,
description: req.input.description,
type: req.input.type,
status: req.input.status,
},
};

console.log('NEW STATE', updatedState);

return updatedState;
}),
});
3 replies
TtRPC
Created by Son on 11/9/2022 in #❓-help
zustand + trpc (basic data fetching)
im trying to use zustand with trpc, but having trouble setting some data to global state. What am i missing here?
import create from 'zustand';
import { trpc } from '../../utils/trpc';

interface TenantState {
tickets: [];
setTickets: any;
}

export const useTenantStore = create<TenantState>()((set, get) => ({
tickets: [],
setTickets: async (newTicket: any[]) => {
set(() => ({ tickets: trpc.ticketService.getByTenantId.useQuery().data })); // problem area
},
}));
import create from 'zustand';
import { trpc } from '../../utils/trpc';

interface TenantState {
tickets: [];
setTickets: any;
}

export const useTenantStore = create<TenantState>()((set, get) => ({
tickets: [],
setTickets: async (newTicket: any[]) => {
set(() => ({ tickets: trpc.ticketService.getByTenantId.useQuery().data })); // problem area
},
}));
i've also tried this with no luck
export const useTenantStore = create<TenantState>()((set, get) => ({
allTickets: {},
fetch: () => {
const data = trpc.ticketService.getByTenantId.useQuery().data;
set({ allTickets: data });
},
}));
export const useTenantStore = create<TenantState>()((set, get) => ({
allTickets: {},
fetch: () => {
const data = trpc.ticketService.getByTenantId.useQuery().data;
set({ allTickets: data });
},
}));
and this...
React.useEffect(() => {
fetch(trpc.ticketService.getByTenantId.useQuery());
}, []);
React.useEffect(() => {
fetch(trpc.ticketService.getByTenantId.useQuery());
}, []);
const fetch = useTenantStore((state) => state.fetch);
const fetch = useTenantStore((state) => state.fetch);
export const useTenantStore = create<TenantState>()((set, get) => ({
allTickets: {},
fetch: async (url: any) => {
const data = url.data;
set({ allTickets: data });
},
}));
export const useTenantStore = create<TenantState>()((set, get) => ({
allTickets: {},
fetch: async (url: any) => {
const data = url.data;
set({ allTickets: data });
},
}));
4 replies
TtRPC
Created by Son on 11/7/2022 in #❓-help
cant access trpc endpoints via the browser
i'm converting some express endpoints to trpc, and I cant figure out how to access my endpoints via the browser for example http://localhost:3000/trpc/getbytenantid my trpc endpoint
export const ticketServiceRouter = router({
getByTenantId: ticketServiceProcedure.query(async () => {
const repo = createRepo();
const tenantId = '908e2d94-aef7-4ba6-a1a3-2ccec65a1d97';

return await repo.get_by_tenant_id({ tenantId });
}),
});
export const ticketServiceRouter = router({
getByTenantId: ticketServiceProcedure.query(async () => {
const repo = createRepo();
const tenantId = '908e2d94-aef7-4ba6-a1a3-2ccec65a1d97';

return await repo.get_by_tenant_id({ tenantId });
}),
});
i get my data in the frontend no problem.
const tickets = trpc.ticketService.getByTenantId.useQuery();
const tickets = trpc.ticketService.getByTenantId.useQuery();
my express endpoint
export const create = (router: Router) => {
const repo = createRepo();

router.get('/tickets/get_by_tenant_id', async (req, res) => {
// Mocked. Should be extracted from the JWT.
const tenantId = '908e2d94-aef7-4ba6-a1a3-2ccec65a1d97';

const result = await repo.get_by_tenant_id({ tenantId });

res.json(result);
});
export const create = (router: Router) => {
const repo = createRepo();

router.get('/tickets/get_by_tenant_id', async (req, res) => {
// Mocked. Should be extracted from the JWT.
const tenantId = '908e2d94-aef7-4ba6-a1a3-2ccec65a1d97';

const result = await repo.get_by_tenant_id({ tenantId });

res.json(result);
});
express adapter
app.use(
'/getTenantById',
trpcExpress.createExpressMiddleware({
router: ticketServiceRouter,
createContext,
})
);
app.use(
'/getTenantById',
trpcExpress.createExpressMiddleware({
router: ticketServiceRouter,
createContext,
})
);
9 replies
TtRPC
Created by Son on 11/4/2022 in #❓-help
trpc + expo react native issue
9 replies