import { useTranslation } from "react-i18next" import styles from…
- User
import { useTranslation } from "react-i18next" import styles from "./build-team.module.css" import { Checkbox } from "../../../ui-component/checkbox/checkbox.component" import { Button } from "../../../ui-component/button/button.component" import { useState } from "react" import { Config } from "../../../utils/config"
const buildItems = [ { image: "../../../public/icons/browser.svg", title: "Front End Developer", width: 40, height: 40, }, { image: "../../../public/icons/product-manager.svg", title: "Product Manager", width: 40, height: 40, }, { image: "../../../public/icons/data-science.svg", title: "Data Science", width: 40, height: 40, }, { image: "../../../public/icons/ux-designer.svg", title: "UX/UI Designer", width: 40, height: 40, }, { image: "../../../public/icons/ai-expert.svg", title: "AI Expert", width: 40, height: 40, }, { image: "../../../public/icons/cloud-engineer.svg", title: "Cloud Engineer", width: 40, height: 40, }, { image: "../../../public/icons/business-metric.svg", title: "Business Metric", width: 40, height: 40, }, { image: "../../../public/icons/backend-developer.svg", title: "Back End Developer", width: 40, height: 40, }, ]
export function BuildTeamType({ selectedProject, setSelectedProject, onNext, }: { selectedProject: string | null setSelectedProject: (projects: string | null) => void onNext: () => void }) { // --------------------------------------------------------------------------- // variables // ---------------------------------------------------------------------------
const { t } = useTranslation() const [loading, setLoading] = useState(false)
// --------------------------------------------------------------------------- // functions // ---------------------------------------------------------------------------
function handleItemClick(title: string) { if (selectedProject === title) { setSelectedProject(null) } else { setSelectedProject(title) } }
async function handleSubmit() { setLoading(true)
const requestData = { title: selectedProject, photoUrl: buildItems.map((item) => item.image).join(" "), } try { const response = await fetch(`${Config.url}/api/team/addKind`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(requestData), credentials: "include", }) if (!response.ok) { throw new Error("Network response was not ok") } const result = await response.json() console.log(result) onNext() } catch (error) { console.error("Error:", error) } finally { setLoading(false) }}
// --------------------------------------------------------------------------- return ( <> {/* --------------------------------------------------------------------------- /} {/ CONTENT /} {/ --------------------------------------------------------------------------- */}
<div className={styles.contentCardWrap}> {buildItems.map((build, index) => ( <div key={index} className={styles.contentCard} onClick={() => handleItemClick(build.title)} > <Checkbox className={styles.checkbox} mode="checkbox" color="#07C96C" size={14} checked={selectedProject === build.title} onClick={() => handleItemClick(build.title)} /> <div className={styles.contentSubWrap}> <img src={build.image} width={build.width} height={build.height} /> <div className={styles.contentTitle}>{build.title}</div> </div> </div> ))} </div> {/* --------------------------------------------------------------------------- */} {/* BUTTONS */} {/* --------------------------------------------------------------------------- */} <div className={styles.nextBtnWrap}> <Button mode="outline" className={styles.nextBtn} disabled={!selectedProject || loading} onClick={handleSubmit} > {loading ? "Loading..." : t("button.next")} </Button> </div> </>) } build-team-type.component.tsx:96 GET http://localhost:9090/ 404 (Not Found)
build-team-type.component.tsx:113 Error: Error: Network response was not ok at handleSubmit (build-team-type.component.tsx:106:15)
- Assistant
It seems like there are a few things that need to be addressed in your
BuildTeamTypecomponent based on the code you've shared and the error logs you've provided. Below are potential areas for improvements and fixes:-
Correcting Image Paths: The image paths you've provided in the
buildItemsarray are relative paths which may not resolve correctly in a web context. Typically, you would reference images in a public directory directly with an absolute path from the public folder. -
API Endpoint Configuration: Ensure the
Config.urlis correctly set up and accessible. If running locally, ensure your server is running and you have the correct endpoint. -
Error Handling Improvements: Enhance error handling to provide more user-friendly feedback in the UI, rather than just logging to the console.
-
Component Improvements: Optimize the checkbox component usage to prevent unwanted click propagation.
Here's a revised version of your component with some improvements:
import { useTranslation } from "react-i18next"; import styles from "./build-team.module.css"; import { Checkbox } from "../../../ui-component/checkbox/checkbox.component"; import { Button } from "../../../ui-component/button/button.component"; import { useState } from "react"; import { Config } from "../../../utils/config"; // Updated Image Paths const buildItems = [ { image: "/icons/browser.svg", title: "Front End Developer", width: 40, height: 40, }, { image: "/icons/product-manager.svg", title: "Product Manager", width: 40, height: 40, }, { image: "/icons/data-science.svg", title: "Data Scientist", // Corrected Title width: 40, height: 40, }, { image: "/icons/ux-designer.svg", title: "UX/UI Designer", width: 40, height: 40, }, { image: "/icons/ai-expert.svg", title: "AI Expert", width: 40, height: 40, }, { image: "/icons/cloud-engineer.svg", title: "Cloud Engineer", width: 40, height: 40, }, { image: "/icons/business-metric.svg", title: "Business Analyst", // Corrected Title width: 40, height: 40, }, { image: "/icons/backend-developer.svg", title: "Back End Developer", width: 40, height: 40, }, ]; export function BuildTeamType({ selectedProject, setSelectedProject, onNext, }: { selectedProject: string | null; setSelectedProject: (projects: string | null) => void; onNext: () => void; }) { const { t } = useTranslation(); const [loading, setLoading] = useState(false); function handleItemClick(title: string) { if (selectedProject === title) { setSelectedProject(null); } else { setSelectedProject(title); } } async function handleSubmit() { setLoading(true); const requestData = { title: selectedProject, photoUrl: buildItems.map((item) => item.image).join(" "), }; try { const response = await fetch(`${Config.url}/api/team/addKind`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(requestData), credentials: "include", }); if (!response.ok) { throw new Error("Network response was not ok"); } const result = await response.json(); console.log(result); onNext(); } catch (error) { console.error("Error:", error); alert("There was an error submitting your request. Please try again."); } finally { setLoading(false); } } return ( <> <div className={styles.contentCardWrap}> {buildItems.map((build, index) => ( <div key={index} className={styles.contentCard} onClick={() => handleItemClick(build.title)} > <Checkbox className={styles.checkbox} mode="checkbox" color="#07C96C" size={14} checked={selectedProject === build.title} onClick={(e) => { e.stopPropagation(); handleItemClick(build.title); }} /> <div className={styles.contentSubWrap}> <img src={build.image} width={build.width} height={build.height} alt={build.title} /> <div className={styles.contentTitle}>{build.title}</div> </div> </div> ))} </div> <div className={styles.nextBtnWrap}> <Button mode="outline" className={styles.nextBtn} disabled={!selectedProject || loading} onClick={handleSubmit} > {loading ? "Loading..." : t("button.next")} </Button> </div> </> ); }Notes:
- The image paths are adjusted to be read from the
publicdirectory properly. - Error handling includes an alert to provide user feedback.
- Stopping the propagation of the click event on the checkbox to prevent triggering the parent div's click event.
- Alt text is added to images for better accessibility.
-
- User
import { useTranslation } from "react-i18next" import styles from "./build-team.module.css" import { Checkbox } from "../../../ui-component/checkbox/checkbox.component" import { Button } from "../../../ui-component/button/button.component" import { useState } from "react" import { Config } from "../../../utils/config"
const buildItems = [ { image: "../../../public/icons/browser.svg", title: "Front End Developer", width: 40, height: 40, }, { image: "../../../public/icons/product-manager.svg", title: "Product Manager", width: 40, height: 40, }, { image: "../../../public/icons/data-science.svg", title: "Data Science", width: 40, height: 40, }, { image: "../../../public/icons/ux-designer.svg", title: "UX/UI Designer", width: 40, height: 40, }, { image: "../../../public/icons/ai-expert.svg", title: "AI Expert", width: 40, height: 40, }, { image: "../../../public/icons/cloud-engineer.svg", title: "Cloud Engineer", width: 40, height: 40, }, { image: "../../../public/icons/business-metric.svg", title: "Business Metric", width: 40, height: 40, }, { image: "../../../public/icons/backend-developer.svg", title: "Back End Developer", width: 40, height: 40, }, ]
export function BuildTeamType({ selectedProject, setSelectedProject, onNext, }: { selectedProject: string | null setSelectedProject: (projects: string | null) => void onNext: () => void }) { // --------------------------------------------------------------------------- // variables // ---------------------------------------------------------------------------
const { t } = useTranslation() const [loading, setLoading] = useState(false)
// --------------------------------------------------------------------------- // functions // ---------------------------------------------------------------------------
function handleItemClick(title: string) { if (selectedProject === title) { setSelectedProject(null) } else { setSelectedProject(title) } }
async function handleSubmit() { setLoading(true)
const requestData = { title: "", photoUrl: "", } try { const response = await fetch(`${Config.url}/api/team/addKind`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(requestData), credentials: "include", }) console.log("response", response) if (!response.ok) { throw new Error("Network response was not ok") } const result = await response.json() console.log(result) onNext() } catch (error) { console.error("Error:", error) } finally { setLoading(false) }}
// --------------------------------------------------------------------------- return ( <> {/* --------------------------------------------------------------------------- /} {/ CONTENT /} {/ --------------------------------------------------------------------------- */}
<div className={styles.contentCardWrap}> {buildItems.map((build, index) => ( <div key={index} className={styles.contentCard} onClick={() => handleItemClick(build.title)} > <Checkbox className={styles.checkbox} mode="checkbox" color="#07C96C" size={14} checked={selectedProject === build.title} onClick={() => handleItemClick(build.title)} /> <div className={styles.contentSubWrap}> <img src={build.image} width={build.width} height={build.height} /> <div className={styles.contentTitle}>{build.title}</div> </div> </div> ))} </div> {/* --------------------------------------------------------------------------- */} {/* BUTTONS */} {/* --------------------------------------------------------------------------- */} <div className={styles.nextBtnWrap}> <Button mode="outline" className={styles.nextBtn} disabled={!selectedProject || loading} onClick={handleSubmit} > {loading ? "Loading..." : t("button.next")} </Button> </div> </>) } I need to send after clicking handle submit only selected title and selected photo. How to do it ?
- Assistant
To send only the selected title and photo URL when the user clicks the submit button, you need to update the
handleSubmitfunction to include this information in the request payload (requestData). Here’s how you can modify your component to achieve that:-
Modify
handleSubmitFunction: Check for the selected project and gather the necessary data (title and photo URL) from thebuildItemsarray. This will populate therequestDatacorrectly. -
Update
buildItemsImage Paths: Ensure the image paths are correct.
Here’s the updated code:
import { useTranslation } from "react-i18next"; import styles from "./build-team.module.css"; import { Checkbox } from "../../../ui-component/checkbox/checkbox.component"; import { Button } from "../../../ui-component/button/button.component"; import { useState } from "react"; import { Config } from "../../../utils/config"; const buildItems = [ { image: "/icons/browser.svg", // Corrected Image Path title: "Front End Developer", width: 40, height: 40, }, { image: "/icons/product-manager.svg", // Corrected Image Path title: "Product Manager", width: 40, height: 40, }, { image: "/icons/data-science.svg", // Corrected Image Path title: "Data Science", width: 40, height: 40, }, { image: "/icons/ux-designer.svg", // Corrected Image Path title: "UX/UI Designer", width: 40, height: 40, }, { image: "/icons/ai-expert.svg", // Corrected Image Path title: "AI Expert", width: 40, height: 40, }, { image: "/icons/cloud-engineer.svg", // Corrected Image Path title: "Cloud Engineer", width: 40, height: 40, }, { image: "/icons/business-metric.svg", // Corrected Image Path title: "Business Metric", width: 40, height: 40, }, { image: "/icons/backend-developer.svg", // Corrected Image Path title: "Back End Developer", width: 40, height: 40, }, ]; export function BuildTeamType({ selectedProject, setSelectedProject, onNext, }: { selectedProject: string | null; setSelectedProject: (project: string | null) => void; onNext: () => void; }) { const { t } = useTranslation(); const [loading, setLoading] = useState(false); function handleItemClick(title: string) { if (selectedProject === title) { setSelectedProject(null); } else { setSelectedProject(title); } } async function handleSubmit() { setLoading(true); const selectedBuild = buildItems.find( (build) => build.title === selectedProject ); const requestData = { title: selectedBuild?.title || "", photoUrl: selectedBuild?.image || "", }; try { const response = await fetch(`${Config.url}/api/team/addKind`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(requestData), credentials: "include", }); if (!response.ok) { throw new Error("Network response was not ok"); } const result = await response.json(); console.log(result); onNext(); } catch (error) { console.error("Error:", error); } finally { setLoading(false); } } return ( <> <div className={styles.contentCardWrap}> {buildItems.map((build, index) => ( <div key={index} className={styles.contentCard} onClick={() => handleItemClick(build.title)} > <Checkbox className={styles.checkbox} mode="checkbox" color="#07C96C" size={14} checked={selectedProject === build.title} onClick={(e) => { e.stopPropagation(); handleItemClick(build.title); }} /> <div className={styles.contentSubWrap}> <img src={build.image} width={build.width} height={build.height} alt={build.title} /> <div className={styles.contentTitle}>{build.title}</div> </div> </div> ))} </div> <div className={styles.nextBtnWrap}> <Button mode="outline" className={styles.nextBtn} disabled={!selectedProject || loading} onClick={handleSubmit} > {loading ? "Loading..." : t("button.next")} </Button> </div> </> ); }Key Changes:
-
Corrected Image Paths: Updated the paths to ensure they are correct and accessible from the
publicdirectory. -
Handle Submit: Updated to find the selected item and send its title and photo URL in the
requestData. -
Component Enhancements:
- Prevented checkbox click event from propagating to the card container.
- Added support for stopping propagation of click events on the checkbox to prevent the event from triggering on the card container.
This way, when the user clicks "Next," only the selected title and image URL are sent to the server.
-
- User
how to send an image to your backend with the fetch() function ?
- Assistant
To send an image to your backend using the
fetchfunction, you'll need to perform a few steps. The general process involves:- Selecting the File: Allow the user to select an image file through an
<input>element withtype="file". - Creating a FormData Object: Store the selected file in a
FormDatainstance, which is easier to work with when dealing with file uploads. - Making the Fetch Request: Send the
FormDataobject in aPOSTrequest to your backend.
Here is how you can achieve this:
-
Add an Input Element for File Selection: Include an
<input>element in your component to allow users to choose an image file. -
Capture the Selected File: Capture the file and store it in the component's state.
-
Create and Send FormData: Use
FormDatato append the image file and other necessary fields for the backend to process.
Here’s an example component showing how to do this:
import React, { useState } from 'react'; import { useTranslation } from 'react-i18next'; import styles from './build-team.module.css'; import { Checkbox } from '../../../ui-component/checkbox/checkbox.component'; import { Button } from '../../../ui-component/button/button.component'; import { Config } from '../../../utils/config'; const buildItems = [ // Your buildItems array here ]; export function BuildTeamType({ selectedProject, setSelectedProject, onNext, }: { selectedProject: string | null; setSelectedProject: (project: string | null) => void; onNext: () => void; }) { const { t } = useTranslation(); const [loading, setLoading] = useState(false); const [selectedFile, setSelectedFile] = useState<File | null>(null); function handleItemClick(title: string) { if (selectedProject === title) { setSelectedProject(null); } else { setSelectedProject(title); } } function handleFileChange(event: React.ChangeEvent<HTMLInputElement>) { const file = event.target.files?.[0] || null; setSelectedFile(file); } async function handleSubmit() { if (!selectedProject || !selectedFile) return; // Ensure a project and file are selected setLoading(true); // Create a FormData object and append title and file const formData = new FormData(); formData.append('title', selectedProject); formData.append('photo', selectedFile); try { const response = await fetch(`${Config.url}/api/team/addKind`, { method: 'POST', body: formData, credentials: 'include', }); if (!response.ok) { throw new Error('Network response was not ok'); } const result = await response.json(); console.log(result); onNext(); } catch (error) { console.error('Error:', error); } finally { setLoading(false); } } return ( <> <div className={styles.contentCardWrap}> {buildItems.map((build, index) => ( <div key={index} className={styles.contentCard} onClick={() => handleItemClick(build.title)} > <Checkbox className={styles.checkbox} mode='checkbox' color='#07C96C' size={14} checked={selectedProject === build.title} onClick={(e) => { e.stopPropagation(); handleItemClick(build.title); }} /> <div className={styles.contentSubWrap}> <img src={build.image} width={build.width} height={build.height} alt={build.title} /> <div className={styles.contentTitle}>{build.title}</div> </div> </div> ))} </div> <div className={styles.nextBtnWrap}> <input type='file' onChange={handleFileChange} /> <Button mode='outline' className={styles.nextBtn} disabled={!selectedProject || !selectedFile || loading} onClick={handleSubmit} > {loading ? 'Loading...' : t('button.next')} </Button> </div> </> ); }Key Points:
-
File Input:
- Added a file input element (
<input type='file' onChange={handleFileChange} />). - Added
handleFileChangeto set the selected file in the state.
- Added a file input element (
-
FormData Usage:
- Created a
FormDataobject. - Appended the
selectedProjectastitleand theselectedFileasphototo theFormDataobject.
- Created a
-
Fetch Request:
- Sent the
FormDataobject in thebodyof the fetch request (body: formData).
- Sent the
The backend should be set up to handle
multipart/form-datarequests to properly process the uploaded file. This approach ensures your file is transmitted correctly, and your backend can access both the file and the associated title. - Selecting the File: Allow the user to select an image file through an
- User
import { useTranslation } from "react-i18next" import styles from "./build-team.module.css" import { Checkbox } from "../../../ui-component/checkbox/checkbox.component" import { Button } from "../../../ui-component/button/button.component" import { Config } from "../../../utils/config" import { useEffect, useState } from "react" import { TeamKindType } from "../../../types/team-kind.type" import { useAuth } from "../../../ui-component/auth-context/auth-context" import { useModal } from "../../../ui-component/modal" import { UserSignInComponent } from "../../user-sign-in/user-sign-in.component" import { useCookies } from "react-cookie" import { CurrentUserType } from "../../../types/user.type"
// const buildItems = [ // { // image: "../../../public/icons/browser.svg", // title: "Front End Developer", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/product-manager.svg", // title: "Product Manager", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/data-science.svg", // title: "Data Science", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/ux-designer.svg", // title: "UX/UI Designer", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/ai-expert.svg", // title: "AI Expert", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/cloud-engineer.svg", // title: "Cloud Engineer", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/business-metric.svg", // title: "Business Metric", // width: 40, // height: 40, // }, // { // image: "../../../public/icons/backend-developer.svg", // title: "Back End Developer", // width: 40, // height: 40, // }, // ]
export function BuildTeamKind({ selectedKinds, setSelectedKinds, onNext, }: { selectedKinds: TeamKindType[] setSelectedKinds: (kinds: TeamKindType[]) => void onNext: () => void }) { // --------------------------------------------------------------------------- // variables // ---------------------------------------------------------------------------
const modal = useModal() const { t: translate } = useTranslation() const { user } = useAuth()
const [kinds, setKinds] = useState<TeamKindType[]>([]) const [currentUser, setCurrentUser] = useState<CurrentUserType | null>(user) const [cookies] = useCookies(["accessToken", "refreshToken"])
// --------------------------------------------------------------------------- // useeffect // ---------------------------------------------------------------------------
useEffect(() => { getAll() }, [])
useEffect(() => { const currentUser = localStorage.getItem("currentUser") if (!currentUser) return setCurrentUser(JSON.parse(currentUser)) }, [cookies, user])
// --------------------------------------------------------------------------- // functions // ---------------------------------------------------------------------------
function handleItemClick(kind: TeamKindType) { if (selectedKinds.some((selected) => selected.id === kind.id)) { setSelectedKinds( selectedKinds.filter((selected) => selected.id !== kind.id), ) } else { setSelectedKinds([...selectedKinds, kind]) } }
async function getAll() { const response = await fetch(
${Config.url}/api/team/kinds, { method: "GET", headers: { "Content-Type": "application/json", }, credentials: "include", })const result: TeamKindType[] = await response.json() setKinds(result)}
// --------------------------------------------------------------------------- return ( <> {/* --------------------------------------------------------------------------- /} {/ CONTENT /} {/ --------------------------------------------------------------------------- */}
<div className={styles.contentCardWrap}> {kinds .sort((a, b) => a.order - b.order) .map((kind) => ( <div key={kind.id} className={styles.contentCard} onClick={() => handleItemClick(kind)} > <Checkbox className={styles.checkbox} mode="checkbox" color="#07C96C" size={14} checked={selectedKinds.some( (selected) => selected.id === kind.id, )} onClick={() => handleItemClick(kind)} /> <div className={styles.contentSubWrap}> <img src={`${Config.imageUrl + kind.photoUrl}`} width={40} height={40} /> <div className={styles.contentTitle}>{kind.title}</div> </div> </div> ))} </div> {/* --------------------------------------------------------------------------- */} {/* BUTTONS */} {/* --------------------------------------------------------------------------- */} <div className={styles.nextBtnWrap}> <Button mode="outline" className={styles.nextBtn} disabled={selectedKinds.length === 0} onClick={() => { currentUser && cookies.accessToken && cookies.refreshToken ? onNext() : modal.open({ component: <UserSignInComponent />, width: "80rem", closeOnEsc: true, closeOnOutsideClick: true, modalClassName: styles.modal, }) }} > {translate("button.next")} </Button> </div> </>) } How can I make my fetch to be called only once
- Assistant
To ensure that your
fetchrequest inside theuseEffecthook runs only once, you need to make sure it depends on an empty dependency array, which signifies that it should be called only on the initial render. Additionally, you should ensure that the function handling the fetch request is defined outside of theuseEffecthook and properly memoized if needed.Based on your provided code, the
getAllfunction is already defined outside ofuseEffect, and theuseEffectrunning thegetAllfunction uses an empty dependency array, which is good practice. Here is a brief review and some enhancements to the current code structure:Refactored Code
import { useTranslation } from "react-i18next"; import styles from "./build-team.module.css"; import { Checkbox } from "../../../ui-component/checkbox/checkbox.component"; import { Button } from "../../../ui-component/button/button.component"; import { Config } from "../../../utils/config"; import { useEffect, useState, useCallback } from "react"; import { TeamKindType } from "../../../types/team-kind.type"; import { useAuth } from "../../../ui-component/auth-context/auth-context"; import { useModal } from "../../../ui-component/modal"; import { UserSignInComponent } from "../../user-sign-in/user-sign-in.component"; import { useCookies } from "react-cookie"; import { CurrentUserType } from "../../../types/user.type"; export function BuildTeamKind({ selectedKinds, setSelectedKinds, onNext, }: { selectedKinds: TeamKindType[]; setSelectedKinds: (kinds: TeamKindType[]) => void; onNext: () => void; }) { // --------------------------------------------------------------------------- // Variables // --------------------------------------------------------------------------- const modal = useModal(); const { t: translate } = useTranslation(); const { user } = useAuth(); const [kinds, setKinds] = useState<TeamKindType[]>([]); const [currentUser, setCurrentUser] = useState<CurrentUserType | null>(user); const [cookies] = useCookies(["accessToken", "refreshToken"]); // --------------------------------------------------------------------------- // useEffect // --------------------------------------------------------------------------- useEffect(() => { getAll(); }, []); useEffect(() => { const currentUser = localStorage.getItem("currentUser"); if (!currentUser) return; setCurrentUser(JSON.parse(currentUser)); }, [cookies, user]); // --------------------------------------------------------------------------- // Functions // --------------------------------------------------------------------------- const handleItemClick = (kind: TeamKindType) => { if (selectedKinds.some((selected) => selected.id === kind.id)) { setSelectedKinds( selectedKinds.filter((selected) => selected.id !== kind.id) ); } else { setSelectedKinds([...selectedKinds, kind]); } }; const getAll = useCallback(async () => { try { const response = await fetch(`${Config.url}/api/team/kinds`, { method: "GET", headers: { "Content-Type": "application/json", }, credentials: "include", }); if (!response.ok) { throw new Error("Network response was not ok"); } const result: TeamKindType[] = await response.json(); setKinds(result); } catch (error) { console.error("Error fetching data:", error); } }, []); // --------------------------------------------------------------------------- return ( <> {/* CONTENT */} <div className={styles.contentCardWrap}> {kinds .sort((a, b) => a.order - b.order) .map((kind) => ( <div key={kind.id} className={styles.contentCard} onClick={() => handleItemClick(kind)} > <Checkbox className={styles.checkbox} mode="checkbox" color="#07C96C" size={14} checked={selectedKinds.some( (selected) => selected.id === kind.id )} onClick={(e) => { e.stopPropagation(); handleItemClick(kind); }} /> <div className={styles.contentSubWrap}> <img src={`${Config.imageUrl + kind.photoUrl}`} width={40} height={40} alt={kind.title} /> <div className={styles.contentTitle}>{kind.title}</div> </div> </div> ))} </div> {/* BUTTONS */} <div className={styles.nextBtnWrap}> <Button mode="outline" className={styles.nextBtn} disabled={selectedKinds.length === 0} onClick={() => { currentUser && cookies.accessToken && cookies.refreshToken ? onNext() : modal.open({ component: <UserSignInComponent />, width: "80rem", closeOnEsc: true, closeOnOutsideClick: true, modalClassName: styles.modal, }); }} > {translate("button.next")} </Button> </div> </> ); }Enhancements and Considerations:
-
Use
useCallbackfor Memoization:- Memoize the
getAllfunction using theuseCallbackhook to prevent unnecessary re-renders or re-creations of the function.
- Memoize the
-
Add Error Handling:
- Wrapped the fetch request in a try-catch block to handle potential errors gracefully and log them.
-
Prevent Checkbox Click Propagation:
- Stopped the propagation of the checkbox click event to prevent it from triggering the surrounding div's click event by using
e.stopPropagation().
- Stopped the propagation of the checkbox click event to prevent it from triggering the surrounding div's click event by using
-
Ensure Correct Dependencies:
- While the empty dependency array in the
useEffectensures the fetch is called only once, ensure any state updates or functions used in it are correctly handled or memoized.
- While the empty dependency array in the
Conclusion
By following these steps, the data fetching will be performed only once on component mount, ensuring that the
getAllfunction doesn't cause unnecessary re-fetches and updates. This approach ensures your application runs efficiently and predictably. -