I have an e-commerce app, and I want to have categories where each category contains different products list based on the category, how I would do that ?
Here is my code
this one called ProductsService.js
const PRODUCTS = [{ id: 100, name: 'ReactProX Headset', price: 350, image: require('../assets/products/product-1.png'), categoryId: "1", description: 'A headset combines a headphone with microphone. Headsets are made with either a single-earpiece (mono) or a double-earpiece (mono to both ears or stereo).'},{ id: 101, name: 'FastLane Toy Car', price: 600, image: require('../assets/products/product-2.png'), categoryId: "2", description: 'A model car, or toy car, is a miniature representation of an automobile. Other miniature motor vehicles, such as trucks, buses, or even ATVs, etc. are often included in this general category.'},{ id: 102, name: 'SweetHome Cupcake', price: 2, image: require('../assets/products/product-3.png'), categoryId: "1", description: 'A cupcake (also British English: fairy cake; Hiberno-English: bun; Australian English: fairy cake or patty cake[1]) is a small cake designed to serve one person.'}];export function getProducts(categoryId) { return PRODUCTS;}export function getProduct(id) { return PRODUCTS.find((product) => (product.id == id));}
this one called Product.js
import React from 'react';import {Text, Image, View, StyleSheet, TouchableOpacity} from 'react-native';export function Product({name, price, image, categoryId ,onPress}) { return (<TouchableOpacity style={styles.card} onPress={onPress}><Image style={styles.thumb} source={image} /><View style={styles.infoContainer}><Text style={styles.name}>{name}</Text><Text style={styles.price}>$ {price}</Text></View></TouchableOpacity> );}
this one called CategoriesList.js
import { SafeAreaView, ScrollView, StatusBar, StyleSheet, Text, useColorScheme, FlatList, View,} from 'react-native';import React, {useEffect, useState} from 'react';import { Product } from '../components/Product.js';import { getProducts } from '../services/ProductsService.js';export function CategoriesList({ route, navigation }) { function renderProduct({item: product}) { return (<Product {...product} onPress={() => { navigation.navigate('ProductDetails', { productId: product.id, }); }} /> ); } const [products, setProducts] = useState([]); useEffect(() => { setProducts(getProducts(route.params)); }); return (<FlatList style={styles.productsList} contentContainerStyle={styles.productsListContainer} keyExtractor={(item) => item.id.toString()} data={products} renderItem={renderProduct} /> );}
I guess the secret is here
export function getProducts(categoryId) {return PRODUCTS;}
but I don't really know how to do it, any help?