Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
17 replies
f2bear

Problems with useQuery.onSuccess()

Hi there, I'm doing a query on my trpc router and when it succeds I want to put that data on a useState that expects a ReactElement based upon the data from the query.

The data from the query response is an array with objects like {id: string, title: string}, when I get them I run a data.forEach() on the returning array but when I have more than one object on the array only one is displayed on the client.

Here is a snippet of what I'm doing, perhaps someone can see what's wrong with my code
const CategoriesIndex = ({ session }: Props) => {
    const [links, setLinks] = useState<ReactElement<typeof CategoryLink>[]>([]);
    api.menu.getSections.useQuery(undefined, {
        enabled: session.user !== undefined,
        onSuccess(data) {
            console.log(data);
            data.forEach((categorie) => {
                setLinks([
                    ...links,
                    <CategoryLink
                        title={categorie.title}
                        id={categorie.id}
                        key={categorie.id}
                        items={0}
                    />,
                ]);
            });
        },
    });
return (
        <div className="col-start-1 col-end-7 row-start-3 grid w-full justify-items-center gap-4">
            <Button
                style="rounded-lg bg-gray-600 h-10 col-start-1 col-end-7 w-full"
                name="add-category"
                label="Añadir sección"
                cb={mutation.mutate}
            />
            {links}
        </div>
    );
Was this page helpful?