Next.js Discord

Discord Forum

data[0].name

Unanswered
American black bear posted this in #help-forum
Open in Discord
Avatar
American black bearOP
I have the following issue that when trying to retrieve my props data it has length of 1 [0, 1] and when console log Array(1) I need to specifiy data[0] in my jsx

jsx   
  <h1 className="text-4xl font-semibold text-black">
                        {data[0]?.name}
    </h1>

... before jsx
    const { slug } = props;

    const categoryQuery = api.category.getCategoryBySlug.useQuery({ slug });

    const router = useRouter()
    if (router.isFallback) {
        return <p>Loading...</p>
    }

    const { data } = categoryQuery;

    
    console.log(data)

export const getStaticProps: GetStaticProps = async (context) => {
    const ssg: SSGHelper = generateSSGHelper();

    const slug = context.params?.category;

    if (typeof slug !== "string") throw new Error("no slug");

    const category = await ssg.category.getCategoryBySlug.prefetch({ slug })

    return {
        props: {
            trpcState: ssg.dehydrate(),
            slug
        },
        revalidate: 60,
    };
};

export const getStaticPaths: GetStaticPaths = async () => {

    const slugs = await prisma.category.findMany({
        select: {
            slug: true,
        },
    });
    return {
        paths: slugs.map((item) => ({
            params: {
                category: item.slug.toString(),
            },
        })),
        fallback: true, // false or "blocking"
    }

};

7 Replies

Avatar
not-milo.tsx
Could you edit the code snippet above for better legibility?

Specify the language after the three backticks like so:
```jsx
const code = "here";
```
But anyways, if the data you're getting back is in the form of an array you'll have to use the standard syntax for accessing its first item. Doesn't matter if there's just one item in it.
Avatar
American black bearOP
yo sorry
i dont know why i have trouble formatting that code syntx
i think it is more of a design problem ive made between the ORM and trpc
dont you think? lol
Avatar
not-milo.tsx
I don't know how you structured your data and api calls and that's up to you. But if you're returning an array then that's how you have to access it. If it's only one element you can change your query to return a single object instead of an array and avoid the bracket syntax.