How to fetch data from a component (client side) and filter data based on data from the server? NextJS13

25 Views Asked by At

Thanks in advance for your help. Context 1st.

I have this categories component ( Categories.tsx) with a hardcoded categories const.

export const categories = [
    {
        label: 'BMW',
        description: 'All BMW cars',
        range: [
            {
                model: "I8", 
                features: ["Electric", "Luxury", "Sport"]
            },
            {
                model: "X6",
                features: ["Gas", "Luxury", "Family"]
            },
            
        ]
    },
    {
        label: 'Lamborghini',
        description: 'All Lamborghini's car',
        range: [
            {
                model: "SVJ",
                features: ["Hybrid", "Luxury", "Sport"]
            },
            {
                model: "Gallardo",
                topics: ["Gas", "Luxury", "Sport"]
            },
        ]
        
    },
    
]

// Rest of the code

I have this getProfiles.ts

import prisma from '@/app/libs/prismadb';
import { categories } from '../components/navbar/Categories';

export interface IProfileParams {
    userId?: string;
    category?: string;
}


export default async function getProfiles({
    params,
    
}: {
    params: IProfileParams;
    
}) {
    try {
        const { 
            userId,
            category,
        } = params;
        
        let query: any = {}

        if (userId) {
            query.userid = userId;
        }

        if (category) {
            // query.category = category
        }
        
        const profiles = await prisma.profile.findMany({
            where: query,
            orderBy: {
                createdAt: 'desc'
            },
            include: {
                user: true
            }
        });

        

        // Rest of the code
        }));

        return safeProfile;
    } catch (error: any) {
        throw new Error(error);
    }
}


GOOD TO KNOW: In my schema.prisma a profile can have multiple model. But I don't save categories. I only saved the array of models.

What I would to do is to filter profiles based on the selected category. To do so (since the related categories are not saved in database), when the user clicks on a category to filter, I need:

  • to update the URL : http://localhost:3000/?category=BMW (It's done :) )
  • Check if the selected category's range includes the saved models ?
  • Then filter based on this info and only show up the profile that has models that are part of the model of the selected category label.

I hope this is clear.

I'm a beginner and I'm trying to understand what is allowed on client-side and server-side and how to handle this type of situation.

Thanks a gain for your help.

I tried to export {categories} from the Categories component but I cannot access .find since the getProfiles.ts is server side.

0

There are 0 best solutions below