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

Did refactoring and added onScroll feature on restaurants page #2

Merged
merged 1 commit into from
Oct 14, 2023
Merged
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ To use this project completely, you need to clone the [online-grocery-app-server
You also need to add an `.env` file at the root of your project that should have following contents:-

- HTTPS=true
- REACT_APP_BASE_URL = http://localhost:4000
- REACT_APP_API_URL = http://localhost:4000
- REACT_APP_GOOGLE_API = https://www.googleapis.com/
- REACT_APP_GG_APP_ID=YOUR_PROJECT_CLIENT_ID

Expand Down
23 changes: 13 additions & 10 deletions src/features/Home/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { useAppDispatch, useAppSelector } from '../../redux/store';
import { setLocation, setLocations } from '../../redux/app.slice';
import axios from 'axios';
import { setSearchParam } from '../../redux/restaurant.slice';
import { TIMEOUT_IN_MILLISECS } from '../../utils/constants';
import { LOCATION_API_URL, TIMEOUT_IN_MILLISECS } from '../../utils/constants';
import { useDebouncedCallback } from 'use-debounce';

const assetsPath = process.env.PUBLIC_URL;
Expand All @@ -24,23 +24,26 @@ const Home = () => {
const dispatch = useAppDispatch();
const location = useAppSelector(state => state.appLevel.location);
const locations = useAppSelector(state => state.appLevel.locations);

useEffect(() => {
axios.get<Array<{ id: string, name: string }>>(`${process.env.REACT_APP_BASE_URL}/locations`)
.then((response) => dispatch(setLocations({ locations: response.data })))
.catch(error => {
console.error(`Error fetching the locations - ${error}`)
});;
}, [dispatch]);

fetchLocation();
}, []);
const fetchLocation = async () => {
try {
const response = await axios.get<Array<{ id: string, name: string }>>(LOCATION_API_URL);
dispatch(setLocations({ locations: response.data }));
}
catch (err) {
dispatch(setLocations({ locations: [] }));
console.error(`Error fecthing the locations - ${err}`);
}
}
const debounced = useDebouncedCallback(
(value) => {
dispatch(setSearchParam({ searchParam: value }));
navigate('order-food-online');
},
TIMEOUT_IN_MILLISECS
);

return (
<>
<div className={`${style.home}`}>
Expand Down
2 changes: 1 addition & 1 deletion src/features/Login/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const Login = () => {
const navigate = useNavigate();
const [appUser, setAppUser] = useState<User>({ email: '', password: '', rememberMe: false });
const authenticateUser = () => {
axios.post<User>(`${process.env.REACT_APP_BASE_URL}/user/authenticate`, appUser)
axios.post<User>(`${process.env.REACT_APP_API_URL}/user/authenticate`, appUser)
.then(response => {
console.log(response.data);
navigate(-1);
Expand Down
44 changes: 29 additions & 15 deletions src/features/OrderOnline/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import { Header } from '../Header';
import style from './orderOnline.module.css';
import { Dropdown } from '../../components/Dropdown';
Expand All @@ -11,7 +11,7 @@ import { setRestaurant, setSearchParam } from '../../redux/restaurant.slice';
import axios from 'axios';
import { Restaurant } from '../../utils/models';
import { setRestaurantList } from '../../utils/service';
import { TIMEOUT_IN_MILLISECS } from '../../utils/constants';
import { RESTAURANT_API_URL, TIMEOUT_IN_MILLISECS } from '../../utils/constants';
import { useDebouncedCallback } from 'use-debounce';

const OrderOnline = () => {
Expand All @@ -21,26 +21,42 @@ const OrderOnline = () => {
const locations = useAppSelector(state => state.appLevel.locations);
const [restaurants, setRestaurants] = useState<Restaurant[]>([]);
const searchString = useAppSelector(state => state.restaurant.searchParam);
const startPage = useRef(0);

useEffect(() => {
axios.get<Restaurant[]>(`${process.env.REACT_APP_BASE_URL}/restaurants/${location}?searchString=${searchString}`)
.then(response => {
setRestaurants(response.data)
setRestaurantList(response.data);
}).catch(error => {
setRestaurants([])
setRestaurantList([]);
console.error(`Error fetching the data - ${error}`)
});
}, [location, searchString]);
fetchRestaurants();
}, [location, searchString, startPage.current]);

useEffect(() => {
window.addEventListener('scroll', onUserScroll);
return () => window.removeEventListener('scroll', onUserScroll);
}, []);

const fetchRestaurants = async () => {
try {
const response = await axios
.get<{ data: Restaurant[] }>(`${RESTAURANT_API_URL}/${location}?searchString=${searchString}&startPage=${startPage.current}`);
setRestaurants([...restaurants, ...response.data.data]);
setRestaurantList([...restaurants, ...response.data.data]);
}
catch (err) {
setRestaurants([])
setRestaurantList([]);
console.error(`Error fetching the restaurants - ${err}`);
}
}
const onUserScroll = () => {
if (window.scrollY + window.innerHeight > document.documentElement.scrollHeight - 700) {
console.log(`curr page ${startPage.current}`);
startPage.current++;
}
}
const debounced = useDebouncedCallback(
(value) => {
dispatch(setSearchParam({ searchParam: value }));
},
TIMEOUT_IN_MILLISECS
);

const headerMenus = [{
id: 'menu1',
element: <Dropdown
Expand All @@ -64,15 +80,13 @@ const OrderOnline = () => {
element: <Link className={`nav-link ${style.navLinkStyle}`} to={'/login'}>Log in</Link>,
parentClassNames: 'ms-auto'
}];

const onRestaurantClick = (restaurantId: string) => {
const selectedRestaurant = restaurants.find(rest => rest.id === restaurantId);
if (selectedRestaurant) {
dispatch(setRestaurant({ restaurant: selectedRestaurant }));
}
navigate('food-menus');
}

return (
<div className={`container`}>
<div className='mt-1'>
Expand Down
4 changes: 3 additions & 1 deletion src/utils/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@ export const CURRENCY: { [key: string]: string } = {
'UK': '£',
'Default': '$'
}
export const TIMEOUT_IN_MILLISECS = 500;
export const TIMEOUT_IN_MILLISECS = 500;
export const LOCATION_API_URL = `${process.env.REACT_APP_API_URL}/locations`;
export const RESTAURANT_API_URL = `${process.env.REACT_APP_API_URL}/restaurants`;
2 changes: 1 addition & 1 deletion src/utils/models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,5 @@ export interface Restaurant {
category: string[];
rating: number;
address: Address;
isOpen: boolean
isOpen: boolean;
}