Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added sort functionality to search and category page #106

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion backend/controllers/productController.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const Product = require('../models/productModel')
// @route GET /api/products
// @access Public
const getProducts = asyncHandler(async (req, res) => {
var sort_type, products
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're using camelCase so, change all occurrences to camelCase. If it is a constant (sort_type) use this naming convention CONSTANT_NAME

Also, don't use var, use const or let. Format the code using the prettier command. Check the package.json file.

const keyword = req.query.keyword
? {
name: {
Expand All @@ -13,8 +14,20 @@ const getProducts = asyncHandler(async (req, res) => {
},
}
: {}
if (req.query.sortby == '0') {
sort_type = 'asc'
} else if (req.query.sortby == '1') {
sort_type = 'desc'
} else {
products = await Product.find({ ...keyword })
}

const products = await Product.find({ ...keyword })
if (sort_type == 'asc' || sort_type == 'desc') {
products = await Product.find({ ...keyword }).sort({ price: sort_type })
} else if (sort_type) {
res.status(404)
throw new Error('Wrong sortby filter')
}
if (products) {
res.json(products)
} else {
Expand Down
23 changes: 20 additions & 3 deletions backend/routes/categoryRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,26 @@ router.get(
router.get(
'/:category',
asyncHandler(async (req, res) => {
const categorywiseProducts = await Product.find({
category: req.params.category,
})
var sort_type, categorywiseProducts
if (req.query.sortby == '0') {
sort_type = 'asc'
} else if (req.query.sortby == '1') {
sort_type = 'desc'
} else {
categorywiseProducts = await Product.find({
category: req.params.category,
})
}

if (sort_type == 'asc' || sort_type == 'desc') {
categorywiseProducts = await Product.find({
category: req.params.category,
}).sort({ price: sort_type })
} else if (sort_type) {
res.status(404)
throw new Error('Wrong sortby filter')
}

// const categorywiseProducts = products.filter((p) => p.category === req.params.category)
if (categorywiseProducts) {
res.json(categorywiseProducts)
Expand Down
39 changes: 23 additions & 16 deletions frontend/src/actions/productActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@ import {
import { logout } from './userActions'

export const listProducts =
(keyword = '') =>
(keyword = '', sortby) =>
async (dispatch) => {
try {
dispatch({ type: PRODUCT_LIST_REQUEST })
const { data } = await axios.get(`/api/products?keyword=${keyword}`)
const { data } = await axios.get(`/api/products`, {
params: { sortby, keyword },
})
dispatch({ type: PRODUCT_LIST_SUCCESS, payload: data })
} catch (error) {
dispatch({
Expand All @@ -41,21 +43,26 @@ export const listProducts =
}
}

export const listProductsByCategory = (category) => async (dispatch) => {
try {
dispatch({ type: PRODUCT_LIST_BY_CATEGORY_REQUEST })
const { data } = await axios.get(`/api/categories/${category}`)
dispatch({ type: PRODUCT_LIST_BY_CATEGORY_SUCCESS, payload: data })
} catch (error) {
dispatch({
type: PRODUCT_LIST_BY_CATEGORY_FAIL,
payload:
error.response && error.response.data.message
? error.response.data.message
: error.message,
})
export const listProductsByCategory =
(category, sortby) => async (dispatch) => {
try {
dispatch({ type: PRODUCT_LIST_BY_CATEGORY_REQUEST })
const { data } = await axios.get(`/api/categories/${category}`, {
params: {
sortby,
},
})
dispatch({ type: PRODUCT_LIST_BY_CATEGORY_SUCCESS, payload: data })
} catch (error) {
dispatch({
type: PRODUCT_LIST_BY_CATEGORY_FAIL,
payload:
error.response && error.response.data.message
? error.response.data.message
: error.message,
})
}
}
}

export const listProductDetails = (id) => async (dispatch) => {
try {
Expand Down
30 changes: 26 additions & 4 deletions frontend/src/screens/CategoryScreen.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, { useEffect } from 'react'
import React, { useEffect, useState } from 'react'
import { Col, Row } from 'react-bootstrap'
import Form from 'react-bootstrap/Form'
import { useDispatch, useSelector } from 'react-redux'
import Product from '../components/Product'
import { listProductsByCategory } from '../actions/productActions'
Expand All @@ -9,13 +10,34 @@ import Message from '../components/Message'
const CategoryScreen = ({ match, history }) => {
const dispatch = useDispatch()
const productList = useSelector((state) => state.productListByCategory)
const [sortBy, setSortBy] = useState()
const { loading, error, products } = productList
useEffect(() => {
dispatch(listProductsByCategory(match.params.category))
}, [dispatch, match])
dispatch(listProductsByCategory(match.params.category, sortBy))
}, [dispatch, match, sortBy])
return (
<>
<h1>Latest Stocks on demand</h1>
<Row>
<Col>
<h1 className="my-auto">Latest Stocks on demand</h1>
</Col>
<Col xs={5} md={3} className="my-auto">
<Form.Group>
<Form.Control
as="select"
value={sortBy}
onChange={(e) => {
setSortBy(e.target.value)
}}
>
<option>Sort By: None</option>
<option value="0">Sort By: Low To High</option>
<option value="1">Sort By: High To Low</option>
</Form.Control>
</Form.Group>
</Col>
</Row>

{loading ? (
<Loader />
) : error ? (
Expand Down
29 changes: 25 additions & 4 deletions frontend/src/screens/SearchScreen.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, { useEffect } from 'react'
import React, { useEffect, useState } from 'react'
import { Col, Row } from 'react-bootstrap'
import Form from 'react-bootstrap/Form'
import { useDispatch, useSelector } from 'react-redux'
import Product from '../components/Product'
import { listProducts } from '../actions/productActions'
Expand All @@ -10,13 +11,33 @@ const SearchScreen = ({ match, history }) => {
const keyword = match.params.keyword
const dispatch = useDispatch()
const productList = useSelector((state) => state.productListBySearch)
const [sortBy, setSortBy] = useState()
const { loading, error, products } = productList
useEffect(() => {
dispatch(listProducts(keyword))
}, [dispatch, match, keyword])
dispatch(listProducts(keyword, sortBy))
}, [dispatch, match, keyword, sortBy])
return (
<>
<h1>Results based on your search</h1>
<Row>
<Col>
<h1 className="my-auto">Results based on your search</h1>
</Col>
<Col xs={5} md={3} className="my-auto">
<Form.Group>
<Form.Control
as="select"
value={sortBy}
onChange={(e) => {
setSortBy(e.target.value)
}}
>
<option>Sort By: None</option>
<option value="0">Sort By: Low To High</option>
<option value="1">Sort By: High To Low</option>
</Form.Control>
</Form.Group>
</Col>
</Row>
{loading ? (
<Loader />
) : error ? (
Expand Down