Skip to content

Commit 18a06fb

Browse files
useReducer Hook
1 parent ca9d17a commit 18a06fb

File tree

2 files changed

+87
-8
lines changed

2 files changed

+87
-8
lines changed

src/context/productcontext.js

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,42 @@
11
import axios from 'axios';
2-
import React, { createContext, useContext, useEffect } from 'react'
2+
import React, { createContext, useContext, useEffect, useReducer } from 'react';
3+
import reducer from "../reducer/productReducer"
34

45
const AppContext = createContext();
56

67
const AppProvider = ({ children }) => {
78

89
const API = "https://api.pujakaitem.com/api/products";
910

10-
const getProduct = async (url)=>{
11-
const res = await axios.get(url)
12-
const product = await res.data
13-
// console.log(res)
14-
console.log(product)
11+
const initialState = {
12+
isLoading:false,
13+
isError:false,
14+
products:[],
15+
featureProducts:[]
16+
}
17+
18+
const[state, dispatch] = useReducer(reducer, initialState)
19+
20+
const getProducts = async (url)=>{
21+
dispatch({try:"SET_LOADING"})
22+
try {
23+
const res = await axios.get(url)
24+
const products = await res.data
25+
// console.log(res)
26+
// console.log(products)
27+
dispatch({type:"MY_API_DATA", payload:products})
28+
} catch (error) {
29+
dispatch({type:"API_ERROR"})
30+
}
1531

1632
}
1733

1834
useEffect(()=>{
19-
getProduct(API)
35+
getProducts(API)
2036
},[])
2137

2238
return (
23-
<AppContext.Provider value={{myName:"Rohit"}}>
39+
<AppContext.Provider value={{...state}}>
2440
{children}
2541
</AppContext.Provider>
2642
)

src/reducer/productReducer.js

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
const productReducer = (state, action) => {
2+
// if(action.type==="SET_LOADING"){
3+
// return{
4+
// ...state,
5+
// isLoading:true
6+
// }
7+
// }
8+
9+
// if(action.type==="MY_API_DATA"){
10+
// const featureData = action.payload.filter((curElem)=>{
11+
// return curElem.featured === true;
12+
// })
13+
// return{
14+
// ...state,
15+
// isLoading:false,
16+
// products:action.payload
17+
// featureProducts:featureData
18+
// }
19+
// }
20+
21+
22+
// if(action.type==="API_ERROR"){
23+
// return{
24+
// ...state,
25+
// isLoading:false,
26+
// isError:true
27+
// }
28+
// }
29+
30+
switch (action.type) {
31+
case "SET_LOADING":
32+
return {
33+
...state,
34+
isLoading: true
35+
}
36+
37+
case "MY_API_DATA":
38+
const featureData = action.payload.filter((curElem) => {
39+
return curElem.featured === true;
40+
})
41+
42+
return {
43+
...state,
44+
isLoading: false,
45+
products: action.payload,
46+
featureProducts: featureData
47+
}
48+
49+
case "API_ERROR":
50+
return {
51+
...state,
52+
isLoading: false,
53+
isError: true
54+
}
55+
56+
57+
58+
default:
59+
return state
60+
}
61+
}
62+
63+
export default productReducer

0 commit comments

Comments
 (0)