Project 2 - Shopping cart application
Context and Reducer:
// AppContext.js
import React, { createContext, useReducer, useContext } from 'react';
const AppContext = createContext();
const initialState = {
products: [],
cart: [],
// other global state properties
};
const appReducer = (state, action) => {
switch (action.type) {
case 'SET_PRODUCTS':
return { ...state, products: action.payload };
case 'ADD_TO_CART':
// Implement logic to add products to the cart
return { ...state, cart: [...state.cart, action.payload] };
// other cases for updating state
default:
return state;
}
};
const AppProvider = ({ children }) => {
const [state, dispatch] = useReducer(appReducer, initialState);
return (
<AppContext.Provider value={{ state, dispatch }}>
{children}
</AppContext.Provider>
);
};
const useAppContext = () => {
return useContext(AppContext);
};
export { AppProvider, useAppContext };
ProductList Component:
// ProductList.js
import React, { useEffect } from 'react';
import { useAppContext } from './AppContext';
const ProductList = () => {
const { state, dispatch } = useAppContext();
useEffect(() => {
// Fetch product data and set it in the global state
const fetchData = async () => {
try {
const response = await fetch('your-api-endpoint');
const data = await response.json();
dispatch({ type: 'SET_PRODUCTS', payload: data.products });
} catch (error) {
console.error('Error fetching product data:', error);
}
};
fetchData();
}, [dispatch]);
return (
<div>
{/* Render the list of products from the global state */}
{state.products.map((product) => (
<ProductCard key={product.id} product={product} />
))}
</div>
);
};
export default ProductList;
FilterBar Component:
// FilterBar.js
import React from 'react';
import { useAppContext } from './AppContext';
const FilterBar = () => {
const { state, dispatch } = useAppContext();
const handleFilterChange = (filterValue) => {
// Update the global state based on the selected filter
// You can implement logic to filter products here
};
return (
<div>
{/* Render filter options and handle changes */}
<select onChange={(e) => handleFilterChange(e.target.value)}>
<option value="all">All</option>
<option value="category1">Category 1</option>
<option value="category2">Category 2</option>
{/* Add more filter options as needed */}
</select>
</div>
);
};
export default FilterBar;