Here is an example of how you could create a React Context API and use the useReducer hook with TypeScript to manage state for a list of Amazon products stored in a Firestore database and more explanation for the code.
import React, { createContext, useReducer, Reducer, useEffect } from 'react';
import { db } from './firebase';
// Create a context for the products
export const ProductsContext = createContext<{
products: Product[];
dispatch: React.Dispatch<ProductAction>;
}>({
products: [],
dispatch: () => {},
});
// Define the types for the state and actions
type Product = {
id: string;
name: string;
price: number;
};
type ProductAction =
| { type: 'ADD'; product: Product }
| { type: 'DELETE'; id: string }
| { type: 'UPDATE'; id: string; product: Product }
| { type: 'SET'; products: Product[] };
// Define the reducer function
const productsReducer: Reducer<Product[], ProductAction> = (state, action) => {
switch (action.type) {
case '
[gs-fb-comments]