Skip to content

Commit

Permalink
stars, swr
Browse files Browse the repository at this point in the history
  • Loading branch information
BelousSofiya committed Oct 19, 2023
1 parent 77bc849 commit 72c3028
Show file tree
Hide file tree
Showing 7 changed files with 191 additions and 152 deletions.
2 changes: 1 addition & 1 deletion FrontEnd/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ function App() {
<Routes>
<Route path="/*" element={<BasicPage />} />
<Route path="/admin/*" element={<AdminPage />} />
<Route path="/search" element={<Search isAuthorized={false} />} />
<Route path="/search" element={<Search isAuthorized={auth} />} />
</Routes>
</div>
</BrowserRouter>
Expand Down
61 changes: 25 additions & 36 deletions FrontEnd/src/components/SearchPage/Search.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import axios from 'axios';
// import { useSWRConfig } from 'swr';
import { useSWRConfig } from 'swr';
import useSWRMutation from 'swr/mutation';
import { useState, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import BreadCrumbs from '../BreadCrumbs/BreadCrumbs';
Expand All @@ -21,48 +22,36 @@ export function Search(props) {
const searchTerm = searchParams.get('name');
const servedAddress = process.env.REACT_APP_BASE_API_URL;
const searchUrl = 'search';
const { mutate } = useSWRConfig();

// useEffect(() => {
// if (searchTerm) {
// // Make an AJAX request to Django API to get search results
// axios
// .get(`${servedAddress}/api/search/?name=${searchTerm}`)
// .then((response) => {
// setSearchResults(response.data);
// setSearchPerformed(true);
// setError(null); // Clear error on successful response
// })
// .catch((error) => {
// console.error('Error fetching search results:', error);
// setError(error.response ? error.response.data : 'An error occurred');
// });
// }
// }, [searchTerm, servedAddress, searchUrl]);
const fetcher = (url) => axios.get(url).then((res) => res.data);

async function getRequest(url) {
const data = await fetcher(url);
setSearchResults(data);
setSearchPerformed(true);
setError(null);
}

const { trigger } = useSWRMutation(
`${servedAddress}/api/search/?name=${searchTerm}`,
getRequest
);

mutate((key) => typeof key === 'string' && key.startsWith('/api/search/'), {
revalidate: true,
});

useEffect(() => {
if (searchTerm) {
// Make an AJAX request to Django API to get search results
axios
.get(`${servedAddress}/api/search/?name=${searchTerm}`)
.then((response) => {
setSearchResults(response.data);
setSearchPerformed(true);
setError(null); // Clear error on successful response
})
.catch((error) => {
console.error('Error fetching search results:', error);
setError(error.response ? error.response.data : 'An error occurred');
});
try {
trigger();
} catch (error) {
console.error(error);
}
}
}, [searchTerm, servedAddress, searchUrl]);

// const fetcher = url => axios.get(url).then(res => res.data)

// function fetchSearchResults () {
// const { data, error } = useSWR('/api/data', fetcher)
// // ...
// }

const [currentPage, setCurrentPage] = useState(1);
const totalItems = searchResults.length;
const totalPages = Math.ceil(totalItems / ITEMS_PER_PAGE);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import MainCompanies from './companies/Companies';
import CompanyCard from './companies/CompanyCard';
import styles from './Text.module.css';

const SearchResults = ({ results, displayedResults, isAuthorized }) => {
Expand All @@ -15,10 +15,7 @@ const SearchResults = ({ results, displayedResults, isAuthorized }) => {
<div className={styles['row']}>
{displayedResults.map((result, resultIndex) => (
<div key={resultIndex} className={styles['col-md-4']}>
<MainCompanies
companyData={result}
isAuthorized={isAuthorized}
/>
<CompanyCard companyData={result} isAuthorized={isAuthorized} />
</div>
))}
</div>
Expand Down
107 changes: 0 additions & 107 deletions FrontEnd/src/components/SearchPage/search_field/companies/Companies.js

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import { Link } from 'react-router-dom';
import { StarOutlined, StarFilled } from '@ant-design/icons';
import { useState, useEffect } from 'react';
import { useSWRConfig } from 'swr';
import useSWRMutation from 'swr/mutation';
// import useSWR from 'swr';
import axios from 'axios';
import styles from './CompanyCard.module.css';

const CompanyCard = ({ companyData, isAuthorized }) => {
const { mutate } = useSWRConfig();
const authToken = localStorage.getItem('Token');
const currentDate = new Date();
const currentYear = currentDate.getFullYear();
const yearsOfExperiense = companyData.founded
? currentYear - companyData.founded
: 0;
const [usersSavedList, setUsersSavedList] = useState([]);
const [star, setStar] = useState(false);
const [isSaved, setIsSaved] = useState(false);

async function sendRequest(url, { arg: data }) {
return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Token ${authToken}`,
},
body: JSON.stringify(data),
}).then();
}

const { trigger } = useSWRMutation(
`${process.env.REACT_APP_BASE_API_URL}/api/saved-list/`,
sendRequest
);

const handleClick = async () => {
try {
await trigger(
{ company_pk: companyData.id },
{ optimisticData: () => setIsSaved(!isSaved) }
);
} catch (error) {
console.error(error);
}
};

mutate((key) => typeof key === 'string' && key.startsWith('/api/profiles/'), {
revalidate: true,
});

const filledStar = (
<StarFilled className={styles['star']} onClick={handleClick} />
);
const outlinedStar = (
<StarOutlined className={styles['star']} onClick={handleClick} />
);

useEffect(() => {
if (isAuthorized)
axios
.get(
`${process.env.REACT_APP_BASE_API_URL}/api/profiles/?is_saved=True`,
{
withCredentials: true,
headers: {
Authorization: 'Token ' + authToken,
},
}
)
.then((response) => {
const NewList = [];
for (let item of response.data.results) {
NewList.push(item['id']);
}

setUsersSavedList(NewList);
if (usersSavedList.includes(companyData.id)) {
setStar(filledStar);
setIsSaved(true);
} else {
setIsSaved(false);
setStar(outlinedStar);
}
})
.catch((error) => {
console.error('Error fetching search results:', error);
});
}, [usersSavedList]);

return (
<div className={styles['product-card']}>
<div className={styles['product-card__block']}>
<div className={styles['product-card__image-frame']}>
<img
className={styles['product-card__image']}
// src={companyData.banner_image}
src={`${process.env.PUBLIC_URL}/companies-logos/defaultcompanybanner.png`}
alt={companyData.name}
/>
</div>
<div className={styles['product-card__text-block']}>
<div className={styles['product-card__text-block__header']}>
<div className={styles['product-card__category-text']}>
{companyData.categories &&
companyData.categories
.map((category) => category.name)
.join(' ')}
</div>
<div className={styles['product-card__name-text']}>
<Link
className={styles['product-card__name-text_link']}
to={`/profile/${companyData.id}`}
>
{companyData.name}
</Link>
<br />
</div>
</div>
<div className={styles['product-card__address-text']}>
{companyData.address}
</div>
<div className={styles['product-card__badges-block']}>
<div className={styles['product-card__badges']}>
<div className={styles['product-card__badge']}>
<div className={styles['product-card__badge-text']}>
{yearsOfExperiense} років досвіду
</div>
</div>
</div>
{/* {isAuthorized ? (isSaved ? filledStar : outlinedStar) : null} */}
{star}
{/* <div>{}</div> */}
</div>
</div>
</div>
<div className={styles['product-card__logo']}>
<div className={styles['product-card__logo-ellipse']}>
<img
className={styles['product-card__logo-image']}
src={`${process.env.PUBLIC_URL}/companies-logos/1.png`}
alt=""
/>
</div>
</div>
</div>
);
};

export default CompanyCard;
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,8 @@
.product-card__buttons:hover {
cursor: pointer;
}

.star {
color: #ffd800;
font-size: 24px;
}
Loading

0 comments on commit 72c3028

Please sign in to comment.