Skip to content

Commit

Permalink
user can search for items
Browse files Browse the repository at this point in the history
  • Loading branch information
j-cort committed Feb 15, 2022
1 parent af7b081 commit a804348
Show file tree
Hide file tree
Showing 8 changed files with 213 additions and 29 deletions.
6 changes: 5 additions & 1 deletion client/src/components/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React, {useState, useEffect} from "react";
import { BrowserRouter, Route } from 'react-router-dom'
import Header from "./Header/Header";
import UserProfile from "./Users/UserProfile";
import ItemSearch from './Items/ItemSearch';
import Main from './Main'
import Alert from "./Alert/Alert";
import './App.css'
Expand All @@ -13,6 +14,7 @@ const App = () => {
const [alert, setAlert] = useState(false)
const [refreshItems, setRefreshItems] = useState(false)
const [profilePic, setProfilePic] = useState(null)
const [searchItems, setSearchItems] = useState(null)

console.log('PROFILE PIC FROM APP', profilePic)
const profilepik = localStorage.getItem('userPic')
Expand All @@ -38,8 +40,10 @@ const App = () => {
<div>
<Header setSession={setSession} session={session} setAlert={setAlert} setRefreshItems={setRefreshItems} profilePic={profilePic} />
<div className="ui container content-field">
<Route path='/' exact render={() => <Main setSession={setSession} session={session} setAlert={setAlert} refreshItems={refreshItems} setRefreshItems={setRefreshItems} profilePic={profilePic}/>}/>
<Route path='/' exact render={() => <Main setSession={setSession} session={session} setAlert={setAlert} refreshItems={refreshItems} setRefreshItems={setRefreshItems} profilePic={profilePic} setSearchItems={setSearchItems}/>}/>
<Route path='/profile' exact render={() => <UserProfile setSession={setSession} session={session} profilePic={profilePic} setProfilePic={setProfilePic} />}/>
<Route path='/items/search/:query' exact render={() => <ItemSearch setSession={setSession} session={session} profilePic={profilePic} setProfilePic={setProfilePic} searchItems={searchItems} setSearchItems={setSearchItems} />}/>

</div>

<Alert alert={alert} setAlert={setAlert} />
Expand Down
7 changes: 4 additions & 3 deletions client/src/components/Items/Item.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import '../../img/image.png'
const Item = ({ item, profilePic, deleteItem, updateItem, uploadImage, borrowItem }) => {

const {_id: id, name, description, images, lender, borrower} = item

console.log(lender.images)
// set rating when we get value from item
let r = Math.floor(Math.random() * 5) + 1;
const RatingStar = () => (
Expand Down Expand Up @@ -51,7 +51,7 @@ const Item = ({ item, profilePic, deleteItem, updateItem, uploadImage, borrowIte
/>

</div>
<img className="ui avatar image" src={lender.images[0] ? lender.images[lender.images.length-1].path : "https://fomantic-ui.com/images/avatar/small/elliot.jpg"} alt="" data-title="blablabla"/>
<img className="ui avatar image" src={lender.images && lender.images[0] ? lender.images[lender.images.length-1].path : "https://fomantic-ui.com/images/avatar/small/elliot.jpg"} alt="" data-title="blablabla"/>
{lender ? `contributed by ${lender.name}` : 'Anon'}
</div>

Expand All @@ -63,7 +63,8 @@ const Item = ({ item, profilePic, deleteItem, updateItem, uploadImage, borrowIte
<div className="ui column centered right floated">

<div className="ui attached segment">
<div className="ui slide masked reveal image tiny">
{/* on mobile make 'large' image to */}
<div className="ui slide masked reveal image large">
<img className="visible content" src={images[0] ? images[0].path : "https://react.semantic-ui.com/images/wireframe/image.png"} alt=""/>
<img src={images[1] ? images[1].path : "https://react.semantic-ui.com//images/avatar/large/elliot.jpg"} class="hidden content" alt=""/>
</div>
Expand Down
4 changes: 4 additions & 0 deletions client/src/components/Items/ItemList.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.main-item-list {
margin-top: 4rem !important;
}

27 changes: 25 additions & 2 deletions client/src/components/Items/ItemList.jsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
import React, { useState, useEffect } from "react";
import { useHistory } from "react-router-dom";
import Item from './Item';
import HomeBanner from '../Home/HomeBanner';
import '../Home/Home.css';
import express from "../../apis/express";
import './ItemList.css'

const ItemList = ({session, refreshItems, setRefreshItems, profilePic}) => {
const ItemList = ({session, refreshItems, setRefreshItems, profilePic, setSearchItems}) => {
let history = useHistory();

const [itemList, setItemList] = useState([])
const [name, setName] = useState("")
const [description, setDescription] = useState("")
const [searchItem, setSearchItem] = useState("")

console.log('SEARCH ITEM UNDER STATE', searchItem)

useEffect(() => {
getItems()
Expand Down Expand Up @@ -85,6 +91,16 @@ const ItemList = ({session, refreshItems, setRefreshItems, profilePic}) => {
getItems()
}

const submitSearch = async (e) => {
e.preventDefault()
console.log('I am searching.......!!!!!!!!')
console.log('SEARCH ITEM IN function', searchItem)
const { data } = await express.get(`/items/search/${searchItem}`)
setSearchItems(data)
history.push(`/items/search/${searchItem}`);
console.log(data)
}

const renderedList = itemList.map(item => {
return (
<Item
Expand All @@ -104,7 +120,14 @@ const ItemList = ({session, refreshItems, setRefreshItems, profilePic}) => {
<HomeBanner />
<div className="main-content">

<div className="ui two stackable cards">
<form onSubmit={submitSearch}>
<div className="ui action icon focus fluid large input">
<input onChange={e => setSearchItem(e.target.value)} type="text" placeholder="Search for items..." />
<i onClick={submitSearch} class="search link icon"></i>
</div>
</form>

<div className="ui one stackable cards main-item-list">
{renderedList}
</div>

Expand Down
148 changes: 148 additions & 0 deletions client/src/components/Items/ItemSearch.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import React, { useState, useEffect } from "react";
import { useHistory } from "react-router-dom";
import Item from './Item';
import HomeBanner from '../Home/HomeBanner';
import '../Home/Home.css';
import express from "../../apis/express";
import './ItemList.css'

const ItemList = ({session, refreshItems, setRefreshItems, profilePic, searchItems, setSearchItems}) => {
console.log('SEARCH PAGE:', searchItems)

let history = useHistory();

const [itemList, setItemList] = useState([])
const [name, setName] = useState("")
const [description, setDescription] = useState("")
const [searchItem, setSearchItem] = useState("")

// useEffect(() => {
// if(searchItems) {
// // display itema
// setSearchItems(false)
// }
// }, [searchItems, searchItems])

useEffect(() => {
getItems()
}, [])

useEffect(() => {
if(refreshItems) {
getItems()
setRefreshItems(false)
}
}, [refreshItems, setRefreshItems])

const getItems = async () => {
const { data } = await express.get('/items')
setItemList(data)
}

const addItem = async (event) => {
event.preventDefault()
if(session) {
const { id: userId } = session.user
const { data } = await express.post('/items', {
item: {
name: name,
description: description,
lender: userId
}
})
}

getItems()
}

const deleteItem = async (id) => {

const { data } = await express.delete(`/items/${id}`)
getItems()
}

const borrowItem = async (id) => {
if(session) {
const { id: userId } = session.user
const { data } = await express.put(`/items/${id}/borrow/${userId}`)
}
getItems()
}

const updateItem = async (event, name, description, lender, borrower, id) => {
event.preventDefault()
// const { data } =
await express.put(`/items/${id}`, {
item: {
name: name,
description: description,
}
})

getItems()
}

const uploadImage = async (event, imageTitle, imageFile, id) => {

event.preventDefault()
let formData = new FormData()
formData.append('title', imageTitle)
formData.append('itemImage', imageFile)

try {
const { data } = await express.post(`/items/${id}/images`, formData)
console.log(data)
} catch(err) {
console.log(err)
}
getItems()
}

const submitSearch = async (e) => {
e.preventDefault()
console.log('I am searching.......!!!!!!!!')
console.log('SEARCH ITEM IN function', searchItem)
const { data } = await express.get(`/items/search/${searchItem}`)
history.push(`/items/search/${searchItem}`);
console.log(data)
}

const renderedList = searchItems.map(item => {
return (
<Item
key={item._id}
item={item}
deleteItem={deleteItem}
updateItem={updateItem}
uploadImage={uploadImage}
borrowItem={borrowItem}
profilePic={profilePic}
/>
)
})

return (
<div>
<HomeBanner />
<div className="main-content">

<form onSubmit={submitSearch}>
<div className="ui action icon focus fluid large input">
<input onChange={e => setSearchItem(e.target.value)} type="text" placeholder="Search for items..." />
<i onClick={submitSearch} class="search link icon"></i>
</div>
</form>

<div className="ui one stackable cards main-item-list">
{renderedList}
</div>

</div>


</div>
)

}

export default ItemList
6 changes: 3 additions & 3 deletions client/src/components/Items/UsersItemsList.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ const UsersItemList = () => {
const userId = user.user.id;


const renderedLendingList = itemList.map(item => {
if (item.lender._id == userId) {
const renderedLendingList = itemList.map(item => {
if (item.lender._id === userId) {
return (
<Item
key={item._id}
Expand All @@ -73,7 +73,7 @@ const UsersItemList = () => {
""
)
} else {
if (item.borrower._id == userId) {
if (item.borrower._id === userId) {
return (

<Item
Expand Down
4 changes: 2 additions & 2 deletions client/src/components/Main.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import React from "react";
import Auth from "./Users/Auth";
import ItemList from "./Items/ItemList";

const Main = ( {session, setSession, setAlert, refreshItems, setRefreshItems, profilePic} ) => {
const Main = ( {session, setSession, setAlert, refreshItems, setRefreshItems, profilePic, setSearchItems} ) => {

if (session) {
return <ItemList session={session} refreshItems={refreshItems} setRefreshItems={setRefreshItems} profilePic={profilePic}/>
return <ItemList session={session} refreshItems={refreshItems} setRefreshItems={setRefreshItems} profilePic={profilePic} setSearchItems={setSearchItems} />
}

return (
Expand Down
40 changes: 22 additions & 18 deletions server/routes/items.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
const express = require("express")
const router = express.Router()
const Item = require("../models/item")
const express = require("express");
const router = express.Router();
const Item = require("../models/item");

// ITEM ROUTES

router.get("/items", async (req, res) => {
const items = await Item.find({})
.populate('borrower')
.populate('lender')
const items = await Item.find({}).populate("borrower").populate("lender");
res.json(items);
});

router.post("/items", async (req, res) => {
const item = new Item(req.body.item);
await item.save();
await item.populate('lender')
await item.populate("lender");
res.json(item);
});

Expand All @@ -24,6 +22,13 @@ router.get("/items/:id", async (req, res) => {
res.json(item);
});

router.get("/items/search/:query", async (req, res) => {
console.log('hit backend')
const { query } = req.params;
const items = await Item.find({name: new RegExp('.*' + query + '.*', "i")})
res.json(items);
});

router.put("/items/:id", async (req, res) => {
const { id } = req.params;
const item = await Item.findByIdAndUpdate(
Expand Down Expand Up @@ -51,20 +56,19 @@ router.put("/items/:id/borrow/:userId", async (req, res) => {
});

// Use multer middleware
const uploadMulter = require('../middleware/images/upload.js')
const validation = require('../middleware/images/validation.js');
const uploadMulter = require("../middleware/images/upload.js");
const validation = require("../middleware/images/validation.js");

router.post("/items/:id/images", uploadMulter, validation, async (req, res) => {
const { id } = req.params;
const item = await Item.findById(id)
const item = await Item.findById(id);

item.images.push({
path: req.file.path
})

await item.save()
res.json(item)

})
path: req.file.path,
});

await item.save();
res.json(item);
});

module.exports = router
module.exports = router;

0 comments on commit a804348

Please sign in to comment.