React & TypeScript: How to use Context API and useReducer with Firestore Database?

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,…

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 'ADD':
      return [...state, action.product];
    case 'DELETE':
      return state.filter((product) => product.id !== action.id);
    case 'UPDATE':
      return state.map((product) =>
        product.id === action.id ? action.product : product
      );
    case 'SET':
      return action.products;
    default:
      return state;
  }
};

// Create a provider component for the products context
const ProductsProvider: React.FC = ({ children }) => {
  const [products, dispatch] = useReducer(productsReducer, []);

  // Load the products from the Firestore database when the component mounts
  useEffect(() => {
    const unsubscribe = db.collection('products').onSnapshot((snapshot) => {
      const products: Product[] = [];
      snapshot.forEach((doc) => {
        products.push({ id: doc.id, ...doc.data() });
      });
      dispatch({ type: 'SET', products });
    });

    // Unsubscribe from the snapshot listener when the component unmounts
    return () => unsubscribe();
  }, []);

  // Return the products context provider with the current state and dispatch function
  return (
    <ProductsContext.Provider value={{ products, dispatch }}>
      {children}
      ...

This is just to show you how to use React and Typescript with Context API and useReducer hook,not a complete app.

Got any questions, please leave a comment.


Print Share Comment Cite Upload Translate
APA
Elham | Sciencx (2024-04-18T16:09:56+00:00) » React & TypeScript: How to use Context API and useReducer with Firestore Database?. Retrieved from https://www.scien.cx/2023/01/09/react-typescript-how-to-use-context-api-and-usereducer-with-firestore-database/.
MLA
" » React & TypeScript: How to use Context API and useReducer with Firestore Database?." Elham | Sciencx - Monday January 9, 2023, https://www.scien.cx/2023/01/09/react-typescript-how-to-use-context-api-and-usereducer-with-firestore-database/
HARVARD
Elham | Sciencx Monday January 9, 2023 » React & TypeScript: How to use Context API and useReducer with Firestore Database?., viewed 2024-04-18T16:09:56+00:00,<https://www.scien.cx/2023/01/09/react-typescript-how-to-use-context-api-and-usereducer-with-firestore-database/>
VANCOUVER
Elham | Sciencx - » React & TypeScript: How to use Context API and useReducer with Firestore Database?. [Internet]. [Accessed 2024-04-18T16:09:56+00:00]. Available from: https://www.scien.cx/2023/01/09/react-typescript-how-to-use-context-api-and-usereducer-with-firestore-database/
CHICAGO
" » React & TypeScript: How to use Context API and useReducer with Firestore Database?." Elham | Sciencx - Accessed 2024-04-18T16:09:56+00:00. https://www.scien.cx/2023/01/09/react-typescript-how-to-use-context-api-and-usereducer-with-firestore-database/
IEEE
" » React & TypeScript: How to use Context API and useReducer with Firestore Database?." Elham | Sciencx [Online]. Available: https://www.scien.cx/2023/01/09/react-typescript-how-to-use-context-api-and-usereducer-with-firestore-database/. [Accessed: 2024-04-18T16:09:56+00:00]
rf:citation
» React & TypeScript: How to use Context API and useReducer with Firestore Database? | Elham | Sciencx | https://www.scien.cx/2023/01/09/react-typescript-how-to-use-context-api-and-usereducer-with-firestore-database/ | 2024-04-18T16:09:56+00:00
https://github.com/addpipe/simple-recorderjs-demo