reduxstore ready

parent e3f3a4da
......@@ -44,32 +44,57 @@ app.get('/products/:id', (req, res) => {
}
})
app.post('/registeruser',(req,res)=>{
const user=req.body
// Middleware function to check if userId already exists
const checkUserIdExists = (req, res, next) => {
const userId = trim(req.body.userId);
db.collection('users').findOne({ userId: userId })
.then(result => {
if (result) {
res.status(400).json({ error: "userId already exists" });
} else {
next(); // Proceed to register user if userId is not taken
}
})
.catch(error => res.status(500).json({ error: "Internal server error" }));
};
// Register User endpoint with middleware
app.post('/registeruser', checkUserIdExists, (req, res) => {
const user = req.body;
const userid=req.body.userId;
db.collection('users').insertOne(user)
.then(result => {
res.status(201).json(result)})
.catch((err)=>res.status(500).json({error:"Could not create a new document"}))
})
res.status(201).json(result);
db.collection('cartitems').insertOne({userId:userid,cartItems:[]})
})
.catch(err => res.status(500).json({ error: "Could not create a new document" }));
});
// Get Users endpoint
app.get('/users', (req, res) => {
db.collection('users').find().toArray()
.then(result => {res.send(result)})
.catch(error => res.status(500).send(error))
})
db.collection('users').find({}, { projection: { _id: false, userId: true, password: true } }).toArray()
.then(result => {
res.send(result);
})
.catch(error => res.status(500).send(error));
});
app.delete('/deregister/:id', (req, res) => {
const Id = req.params.id
if(ObjectId.isValid(Id)){
db.collection('users').deleteOne({_id:new ObjectId(Id)})
.then(result => { res.send(result) })
app.delete('/deregister/:userid', (req, res) => {
const userid = req.params.userid
if(isNaN(userid)){
db.collection('users').deleteOne({userId:userid})
.then(result => {
res.send(result)
db.collection('cartitems').deleteOne({userId:userid})
})
.catch(error => res.status(500).send(error))
} else {
res.status(500).json({ error: 'Invalid ID' })
}
})
app.patch('/update/:id', (req, res) => {
app.patch('/updateuser/:id', (req, res) => {
const Id = req.params.id
const data = req.body
if(ObjectId.isValid(Id)){
......@@ -80,3 +105,29 @@ app.patch('/update/:id', (req, res) => {
res.status(500).json({ error: 'Invalid ID' })
}
})
app.get('/cartItems/:userid', (req, res) => {
const userid = req.params.userid
if(isNaN(userid)){
db.collection('cartitems').find({userId: userid}).toArray()
.then(result => { res.send(result) })
.catch(error => res.status(500).send(error))
} else {
res.status(500).json({ error: 'Invalid UserId' })
}
})
app.post('/updateCartItems/:userid', (req, res) => {
const userid=req.params.userid
const newCartItems = req.body
console.log(newCartItems)
if(isNaN(userid)){
db.collection('cartitems').updateOne({userId: userid},{$set:{cartItems:newCartItems}})
.then(result => { res.send(result).status(200) })
.catch(error => res.status(500).send(error))
} else {
res.status(500).json({ error: 'Invalid UserId' })
}
})
......@@ -4,21 +4,28 @@ import { fetchProducts,ProductsStateType } from '../reduxstore/productsSlice';
import { fetchUsers,UsersStateType } from '../reduxstore/usersSlice';
import {useDispatch,useSelector } from 'react-redux';
import { RootState } from '../reduxstore/store';
import { fetchCartItems } from '../reduxstore/cartSlice';
import { updateCartItems ,UpdateCartStateType} from '../reduxstore/updatecartSlice';
const Home = memo(() => {
const dispatch=useDispatch()
const users=useSelector((state:RootState)=> state.users.users)
const users=useSelector((state:RootState)=> state.cart.cartItems)
const Items=[{"_id":"65cc84a4a897e49b4c752f23","id":1,"title":"Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops","price":109.95,"description":"Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday","category":"men's clothing","image":"https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg","rating":{"rate":3.9,"count":120}},{"_id":"65cc84a4a897e49b4c752f24","id":2,"title":"Mens Casual Premium Slim Fit T-Shirts ","price":22.3,"description":"Slim-fitting style, contrast raglan long sleeve, three-button henley placket, light weight & soft fabric for breathable and comfortable wearing. And Solid stitched shirts with round neck made for durability and a great fit for casual fashion wear and diehard baseball fans. The Henley style round neckline includes a three-button placket.","category":"men's clothing","image":"https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg","rating":{"rate":4.1,"count":259}},{"_id":"65cc84a4a897e49b4c752f25","id":3,"title":"Mens Cotton Jacket","price":55.99,"description":"great outerwear jackets for Spring/Autumn/Winter, suitable for many occasions, such as working, hiking, camping, mountain/rock climbing, cycling, traveling or other outdoors. Good gift choice for you or your family member. A warm hearted love to Father, husband or son in this thanksgiving or Christmas Day.","category":"men's clothing","image":"https://fakestoreapi.com/img/71li-ujtlUL._AC_UX679_.jpg","rating":{"rate":4.7,"count":500}}]
useEffect(() => {
dispatch(fetchUsers());
dispatch(fetchProducts());
}, []);
const testDispatch=useCallback(()=>{
console.log(users)
dispatch(updateCartItems({userId:"bhanu",updateCartlist:Items}))
},[users])
useEffect(() => {
dispatch(fetchUsers());
dispatch(fetchProducts());
dispatch(fetchCartItems("bhanu"))
}, []);
return (
<div>
Home
......
import { createSlice } from "@reduxjs/toolkit"
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
const initialState={
numOfCakes:10,
}
type cartStateType = {
loading: boolean;
cartItems: any[];
error: string | undefined;
};
const cakeSlice=createSlice({
name:'cake',
initialState,
reducers:{
ordered:(state)=>{
state.numOfCakes--
},
restocked:(state,action)=>{
state.numOfCakes+=action.payload
},
},
})
export default cakeSlice.reducer
export const{ordered,restocked}=cakeSlice.actions
const initialState: cartStateType = {
loading: false,
cartItems: [],
error: ''
};
export const fetchCartItems:any= createAsyncThunk('cart/fetchCartItems', async (userid) => {
return await axios.get(`http://localhost:4000/cartItems/${userid}`)
.then(response => response.data);
});
const cartSlice = createSlice({
name: 'cartItems',
initialState,
reducers: {},
extraReducers: builder => {
builder.addCase(fetchCartItems.pending, (state) => {
state.loading = true;
state.error="pending"
});
builder.addCase(fetchCartItems.fulfilled, (state, action) => {
state.loading = false;
state.cartItems = action.payload;
state.error = '';
});
builder.addCase(fetchCartItems.rejected, (state, action) => {
state.loading = false;
state.cartItems = [];
state.error = action.error || 'Something went wrong!';
});
}
});
export default cartSlice.reducer;
export type CartStateType = ReturnType<typeof cartSlice.reducer>;
import { configureStore } from '@reduxjs/toolkit'
import cartReducer from './cartSlice'
import cartReducer,{CartStateType} from './cartSlice'
import productsReducer,{ProductsStateType} from './productsSlice'
import usersReducer,{UsersStateType} from './usersSlice'
export type RootState= {
products:ProductsStateType;
cart: any;
cart: CartStateType;
users: UsersStateType;
}
const store=configureStore({
......
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
type updateCartStateType = {
loading: boolean;
cartItems: any[];
error: string | undefined;
};
type CartItemType = {
userId:string,
updateCartlist:any[]
}
const initialState: updateCartStateType = {
loading: false,
cartItems: [],
error: ''
};
export const updateCartItems:any= createAsyncThunk('updatecart/updateCartItems', async ({userId,updateCartlist}:CartItemType) => {
return await axios.post(`http://localhost:4000/updateCartItems/${userId}`,updateCartlist)
.then(response => response.data);
});
const updatecartSlice = createSlice({
name: 'updatecartItems',
initialState,
reducers: {},
extraReducers: builder => {
builder.addCase(updateCartItems.pending, (state) => {
state.loading = true;
state.error="pending"
});
builder.addCase(updateCartItems.fulfilled, (state, action) => {
state.loading = false;
state.cartItems = action.payload;
state.error = '';
});
builder.addCase(updateCartItems.rejected, (state, action) => {
state.loading = false;
state.cartItems = [];
state.error = action.error || 'Something went wrong!';
});
}
});
export default updatecartSlice.reducer;
export type UpdateCartStateType = ReturnType<typeof updatecartSlice.reducer>;
import { createSlice } from "@reduxjs/toolkit"
type UserDetailsType={
userDetails:any[]|null
}
const initialState:UserDetailsType={
userDetails:[],
}
const userDetailsSlice=createSlice({
name:'userDetails',
initialState,
reducers:{
loginUser:(state,action)=>{
state.userDetails=action.payload
},
logoutUser:(state)=>{
state.userDetails=[]
},
},
})
export default userDetailsSlice.reducer
export const{loginUser,logoutUser}=userDetailsSlice.actions
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment