Untitled
1 week ago in JavaScript
import {useEffect, useState} from "react";
import {apiClient} from "../api/axios.ts";
interface CompanyDetailsHook {
company: Company | null;
error: string | null;
handleRoleChange: (userId: string, newRole: string) => void;
loading: boolean;
}
export interface Company{
id:string
name: string
description: string
avatarUrl: string;
members: User[];
}
interface User {
id: string;
name: string;
role: string;
}
const useCompanyDetails = (companyId: string):CompanyDetailsHook => {
const [company, setCompany] = useState<Company | null>(null);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
useEffect(() => {
const fetchCompanyDetails = async () => {
try {
const response = await apiClient.get(`/details/${companyId}`);
setCompany(response.data);
} catch (err) {
console.error('Error fetching company details:', err);
setError("Failed to load company details");
} finally {
setLoading(false);
}
};
if (companyId) {
fetchCompanyDetails();
} else {
console.error("Invalid companyId:", companyId);
}
}, [companyId]);
const handleRoleChange = async (userId: string, newRole: string) => {
try {
await apiClient.put(`/company/${companyId}/member/${userId}/role`, { role: newRole });
setCompany((prevCompany) =>
prevCompany
? {
...prevCompany,
members: prevCompany.members.map((member) =>
member.id === userId ? { ...member, role: newRole } : member
),
}
: prevCompany
);
} catch (err) {
console.error('Error updating role:', err);
setError("Failed to update role");
}
};
return {company, error, handleRoleChange, loading};
};
export default useCompanyDetails;
///////////////////////////////////
import React from "react";
import { useParams } from 'react-router-dom';
import useCompanyDetails from "../../../hooks/useCompanyDetails.ts";
const CompanyDetailPage: React.FC = () => {
const { companyId } = useParams<{ companyId: string }>();
console.log(companyId);
const {company, error, handleRoleChange} = useCompanyDetails(companyId!);
if (error) return <p>{error}</p>;
if (!company) return <p>Company ID is missing.</p>;
return (
<div>
<h2>{company.name}</h2>
<p>{company.description}</p>
<h3>Members</h3>
<ul>
{company.members.map((member) => (
<li key={member.id}>
<span>{member.name}</span>
<select
value={member.role}
onChange={(e) => handleRoleChange(member.id, e.target.value)}
>
<option value="member">Member</option>
<option value="manager">Manager</option>
<option value="admin">Admin</option>
</select>
</li>
))}
</ul>
</div>
)
}
export default CompanyDetailPage;
//////
router.get('/details/:companyId', async (req, res) => {
const companyId = req.params.companyId;
try {
const companyRepo = AppDataSource.getRepository(Company);
const company = await companyRepo.findOne({
where: { company_id: companyId },
relations: ['members'],
})
if (!company) {
res.status(404).json({message: 'Company not found'})
return
}
res.status(200).json(company);
} catch (error) {
console.log('Error fetching company details:', error);
res.status(500).json({message: 'Server error'})
}
})