import React, { useState, useEffect, useContext } from "react"; import Select from…
- User
import React, { useState, useEffect, useContext } from "react"; import Select from "react-select"; import { useForm, Controller } from "react-hook-form"; // import { categories } from "../../helpers/constants"; import { toast } from "react-toastify"; import "react-datepicker/dist/react-datepicker.css"; import { useNavigate } from "react-router-dom";
// API import { createCampaign, getTags, getProfile } from "../../api"; import { AuthContext } from "../../context/authContext";
// HOOKS import useApp from "../../hooks/useApp";
import { FixedSizeList as List } from "react-window";
const DropdownVirtualizedMenu = (props) => { const children = React.Children.toArray(props.children); return ( <List height={300} // Adjust height as needed itemCount={children.length} itemSize={40} // Height of each item width={400} borderWidth={2} > {({ index, style }) => ( <div style={{ ...style, // Spread the dynamic style from the virtualized list backgroundColor: "#1a212d", // Ensure the background color is preserved overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis", width: "100%", wordBreak: "break-word", // Break long words when necessary overflowWrap: "break-word", padding: "0 5px", }} > {children[index]} )} ); };
function CampaignForm() { const { isAuthenticated } = useContext(AuthContext); const [user, setUser] = useState(null);
const [categories, setCategories] = useState([]); const [subcategories, setSubcategories] = useState([]); // State for subtags
const [contributionPerHead, setContributionPerHead] = useState(0); // State for contribution per head
useEffect(() => { // Fetch tags when component mounts const fetchTags = async () => { try { if (isAuthenticated) { const profileResponse = await getProfile(); setUser(profileResponse.data); }
const tags = await getTags(); // Fetch tags from API const formattedTags = tags.data.map((tag) => ({ value: tag.name, label: tag.name, subtags: tag.subtags, })); // Format tags for categories setCategories(formattedTags); // Update state } catch (error) { console.error("Failed to fetch tags:", error); } }; fetchTags(); // Call the fetch function}, [isAuthenticated]);
const navigate = useNavigate(); const { setTransactionLoading } = useApp(); const [submit, setSubmit] = useState(false); const [image, setImage] = useState(null); // Add state for the image
const { register, control, handleSubmit, formState: { errors }, watch, setValue, } = useForm({ defaultValues: { profit: "no", }, });
const goal = watch("goal"); const participantSlots = watch("participantSlots"); const profit = watch("profit");
useEffect(() => { if (goal && participantSlots) { const baseContribution = goal / participantSlots; // Base contribution
// Determine multiplier based on profit const multiplier = profit === "yes" ? 0.2 : 0.1; const fee = multiplier * baseContribution; // Calculate fee // Format the output as desired const formattedContribution = `Contribution per head: ${baseContribution.toFixed( 2 )} (+ ${fee.toFixed(2)}) USD`; setContributionPerHead(formattedContribution); // Update state with formatted contribution } else { setContributionPerHead(""); // Reset if no goal or slots }}, [goal, participantSlots, profit]); // Add profit to dependencies
/* --------------------------------------------- HANDLE REGISTER FORM SUBMIT --------------------------------------------- */ async function handleFormSubmit(data) { try { setTransactionLoading(true); setSubmit(true);
const formData = new FormData(); // Use FormData for image upload formData.append("goalAmount", data.goal); // Matching backend goalAmount formData.append("title", data.title); formData.append("description", data.description); // Ensure category is a string const category = data.category ? data.category.value : ""; formData.append("tags", category); formData.append("subtags", data.subtag.value); // Add subtags formData.append("profit", data.profit); // Add profit formData.append("participantSlots", data.participantSlots); // Add participantSlots formData.append("image", image); // Check if the user's status is active if (user && user.status !== "active") { toast.error("Please complete pending actions in your profile first."); setSubmit(false); setTimeout(() => { window.location.reload(); }, 3000); return; } // Make the API request const response = await createCampaign(formData); // Check if the response status is 201 if (response.status === 201) { toast.success("Campaign created successfully!"); navigate(`/campaigns/${response.data._id}`); // Redirect to campaigns page setTimeout(() => { window.location.reload(); }, 3000); } else { throw new Error("Failed to create campaign"); } } catch (error) { setSubmit(false); // Check for error code and provide custom messages based on status code if (error.response) { switch (error.response.status) { case 400: toast.error( "Insufficient funds. Please add more funds to proceed." ); setTimeout(() => { window.location.reload(); }, 2000); break; case 500: toast.error( "Incorrect image format. Only PNG and JPG are allowed." ); setTimeout(() => { window.location.reload(); }, 2000); break; default: toast.error("An unexpected error occurred. Please try again."); setTimeout(() => { window.location.reload(); }, 2000); } } else if (error.message) { toast.error(error.message || "Something went wrong"); setTimeout(() => { window.location.reload(); }, 2000); } else { toast.error("An unknown error occurred"); // wait 2 seconds then reload the page setTimeout(() => { window.location.reload(); }, 2000); } } finally { setTransactionLoading(false); }}
//handle tag change
useEffect(() => { setSubcategories([]); // Reset subtags when the tag changes }, [categories]);
// Function to handle tag change and update subtags const handleTagChange = (selectedTag) => { setValue("subtag", null); // Reset subtag value if (selectedTag && selectedTag.subtags) { // If a tag is selected, set its subtags const formattedSubtags = selectedTag.subtags.map((subtag) => ({ value: subtag, label: subtag, })); setSubcategories(formattedSubtags); // Update the subtags list } else { // If no tag or "All" is selected, clear the subtags list setSubcategories([]); // This will trigger re-render } };
/* --------------------------------------------- HANDLE IMAGE UPLOAD --------------------------------------------- */ const handleImageChange = (e) => { const file = e.target.files[0]; setImage(file); };
return ( <> {!submit && ( {/* TITLE */} Title <input type="text" className={
form-control ${errors.title ? "is-invalid" : ""}} id="title" placeholder="Enter campaign title name" name="title" maxLength="29" // Limit input to 40 characters {...register("title", { required: { value: true, message: "Enter campaign title name", }, maxLength: { value: 40, message: "Title must be at most 40 characters", }, })} /> {errors.title && ( {errors.title?.message} )}{/* DESCRIPTION */} <div className="col-lg-12"> <label className="form-label" htmlFor="description"> Description </label> <textarea rows="7" className={`form-control ${ errors.description ? "is-invalid" : "" }`} id="description" placeholder="Enter the campaign description" name="description" {...register("description", { required: { value: true, message: "Enter the campaign description", }, minLength: { value: 40, message: "Campaign description must be more than 40 characters", }, })} ></textarea> {errors.description && ( <span className="invalid-feedback"> {errors.description?.message} </span> )} </div> {/* GOAL */} <div className="col-lg-6"> <label className="form-label" htmlFor="goal"> Goal - USD </label> <input type="number" step="1" className={`form-control ${errors.goal ? "is-invalid" : ""}`} id="goal" placeholder="Enter your campaign goal" name="goal" {...register("goal", { required: { value: true, message: "Enter your campaign goal", }, min: { value: 1, message: "Goal must be at least 1 USD", }, })} /> {errors.goal && ( <span className="invalid-feedback">{errors.goal?.message}</span> )} </div> {/* PARTICIPANT SLOTS */} <div className="col-lg-6"> <label className="form-label" htmlFor="participantSlots"> Participant Slots </label> <input type="number" className={`form-control ${ errors.participantSlots ? "is-invalid" : "" }`} id="participantSlots" placeholder="Enter the number of participant slots" name="participantSlots" {...register("participantSlots", { required: { value: true, message: "Enter the number of participant slots", }, min: { value: 2, message: "There must be at least 2 participant slot", }, })} /> {errors.participantSlots && ( <span className="invalid-feedback"> {errors.participantSlots?.message} </span> )} </div> {/* Add 10% profit YesorNo */} <div className="col-lg-12"> <label className="form-label text-primary" htmlFor="profit"> Add 10% profit? </label> <Controller name="profit" control={control} rules={{ required: "Please select an option" }} render={({ field }) => ( <Select {...field} options={[ { value: "yes", label: "Yes" }, { value: "no", label: "No" }, ]} id="profit" className={`border-0 shadow-sm ${ errors.profit ? "is-invalid" : "" }`} classNamePrefix="select" value={ field.value ? { value: field.value, label: field.value === "yes" ? "Yes" : "No", } : { value: "no", label: "No" } // Inline default value set to "No" } // Set value based on field onChange={(selectedOption) => field.onChange(selectedOption?.value) } /> )} /> {errors.profit && ( <span className="invalid-feedback"> {errors.profit?.message} </span> )} </div> {/* CATEGORY */} <div className="col-lg-6"> <label className="form-label" htmlFor="category"> Category </label> <Controller name="category" control={control} rules={{ required: "Please select a category" }} render={({ field }) => ( <Select components={{ MenuList: DropdownVirtualizedMenu }} options={categories} id="category" className={`border-0 shadow-sm ${ errors.category ? "is-invalid" : "" }`} classNamePrefix="select" placeholder="Select" isSearchable={true} onChange={(selectedOption) => { field.onChange(selectedOption); handleTagChange(selectedOption); // Update subtags }} /> )} /> {errors.category && ( <span className="invalid-feedback"> {errors.category?.message} </span> )} </div> {/* SUBTAG */} <div className="col-lg-6"> <label className="form-label" htmlFor="subtag"> Sub-Category </label> <Controller name="subtag" control={control} rules={{ required: "Please select a sub-category" }} render={({ field }) => ( <Select components={{ MenuList: DropdownVirtualizedMenu }} options={subcategories} id="subtag" className={`border-0 shadow-sm ${ errors.subtag ? "is-invalid" : "" }`} classNamePrefix="select" placeholder="Select" isSearchable={true} {...field} /> )} /> {errors.subtag && ( <span className="invalid-feedback"> {errors.subtag?.message} </span> )} </div> {/* Show contribution per head */} <div className="col-lg-12 text-muted"> <p> {contributionPerHead}{" "} {/* This will now display the formatted string */} </p> </div> <div className="col-lg-12"> <p> Note: The campagn creator needs to make the first contribution, so make sure you have sufficient balance to create the campaign. </p> </div> {/* CAMPAIGN IMAGE */} <div className="col-lg-12"> <label className="form-label" htmlFor="image"> Campaign Image </label> <input type="file" className={`form-control ${errors.image ? "is-invalid" : ""}`} id="image" accept="image/png, image/jpeg" {...register("image", { required: { value: true, message: "Please upload a campaign image", }, validate: { acceptedFormats: (file) => file[0]?.type === "image/png" || file[0]?.type === "image/jpeg" || "Only PNG and JPEG formats are allowed", }, })} onChange={handleImageChange} // Handle image upload /> {errors.image && ( <span className="invalid-feedback"> {errors.image?.message} </span> )} </div> {/* SUBMIT */} <div className="col-12"> <button className="btn btn-primary" type="submit"> Create Campaign </button> </div> </div> </form> )} </>); }
export default CampaignForm;
so now, i want to change the profit thing from yes no to integer amount (min 0, default 0)
profit fee will be profit/no.ofparticipants
just give code lines needed to change, not full code
- Assistant
To change the profit selection from a Yes/No toggle to an integer input where the profit fee is distributed across the number of participants, you can modify the
profitsection of your code as follows:-
Change the Profit Input Field: Replace the current
<Select>component for profit with an<input>field for numerical input.{/* PROFIT */} <div className="col-lg-6"> <label className="form-label" htmlFor="profit"> Profit - USD </label> <input type="number" step="1" className={`form-control ${errors.profit ? "is-invalid" : ""}`} id="profit" placeholder="Enter profit amount" name="profit" {...register("profit", { required: { value: true, message: "Enter profit amount", }, min: { value: 0, message: "Profit must be at least 0 USD", }, })} /> {errors.profit && ( <span className="invalid-feedback">{errors.profit?.message}</span> )} </div> -
Update the Effect to Calculate Contribution: Adjust the calculation by replacing the
multiplierwith the actual profit value divided by the number of participants.useEffect(() => { if (goal && participantSlots) { const baseContribution = goal / participantSlots; // Base contribution const profitValue = parseFloat(profit) || 0; // Parse the profit value const fee = profitValue / participantSlots; // Calculate fee // Format the output as desired const formattedContribution = `Contribution per head: ${baseContribution.toFixed( 2 )} (+ ${fee.toFixed(2)}) USD`; setContributionPerHead(formattedContribution); // Update state with formatted contribution } else { setContributionPerHead(""); // Reset if no goal or slots } }, [goal, participantSlots, profit]);
With these changes, the profit will now be an integer input amount that gets distributed among participants, and the contribution per head will reflect this update.
-
- User
only integer allowed, also no negatives
- Assistant
To ensure that only non-negative integers are allowed for the profit input, you can adjust the validation rules in the
useFormsetup for theprofitfield. Here's how you can modify the input field to allow only non-negative integers:-
Update the Profit Input Validation:
Use the
validateoption inregisterto check for integer values and ensure no negative numbers are allowed.{/* PROFIT */} <div className="col-lg-6"> <label className="form-label" htmlFor="profit"> Profit - USD </label> <input type="number" step="1" className={`form-control ${errors.profit ? "is-invalid" : ""}`} id="profit" placeholder="Enter profit amount" name="profit" {...register("profit", { required: { value: true, message: "Enter profit amount", }, min: { value: 0, message: "Profit must be at least 0 USD", }, validate: { integer: (value) => Number.isInteger(parseFloat(value)) || "Profit must be an integer", }, })} /> {errors.profit && ( <span className="invalid-feedback">{errors.profit?.message}</span> )} </div>
In this setup, the
validateoption is used to ensure the input is an integer. Additionally, theminvalidation rule prevents negative numbers. The input field type remains asnumberwith a step of 1 to restrict input to integers through the browser interface. -
- User
not after clicking, i want it live
- Assistant
To validate the input to ensure only non-negative integers are allowed in real-time, you can listen for the
onChangeevent and manually adjust the input value. Here's how you can implement this:-
Modify the Profit Input to React to Changes:
Use
onChangeto ensure the entered value is a non-negative integer. This involves handling invalid characters or formatting live as the user types:{/* PROFIT */} <div className="col-lg-6"> <label className="form-label" htmlFor="profit"> Profit - USD </label> <input type="text" // Use text to control the input className={`form-control ${errors.profit ? "is-invalid" : ""}`} id="profit" placeholder="Enter profit amount" name="profit" value={watch('profit') || ''} // Use watch to keep track of the input state onChange={(e) => { const value = e.target.value; // Allow only non-negative integers if (/^\d*$/.test(value)) { setValue('profit', value); // Update the form value } }} {...register("profit", { required: { value: true, message: "Enter profit amount", }, })} /> {errors.profit && ( <span className="invalid-feedback">{errors.profit?.message}</span> )} </div>Key Points:
- Type
text: By setting thetypetotext, you can intercept all input changes and use regex to restrict them. - Regex Validation: Use a regular expression (
/^\d*$/) to allow only digits, effectively preventing negative signs and non-integer input. - Update Form Value: Use
setValuefromreact-hook-formto update the form value whenever valid input is entered.
- Type
This change ensures that as a user types, only valid non-negative integers are accepted, providing immediate feedback and correction without additional user actions.
-
- User
also integer no decimal
- Assistant
To ensure that the input field only accepts non-negative integers without decimals in real-time, you can use a combination of input type, regex validation, and real-time change handling. Here's how you can modify your input to achieve this behavior:
{/* PROFIT */} <div className="col-lg-6"> <label className="form-label" htmlFor="profit"> Profit - USD </label> <input type="text" // Use text to control the input precisely className={`form-control ${errors.profit ? "is-invalid" : ""}`} id="profit" placeholder="Enter profit amount" name="profit" value={watch('profit') || ''} // Keep input state in sync onChange={(e) => { const value = e.target.value; // Allow only non-negative integers: test against a regex for whole numbers if (/^\d*$/.test(value)) { setValue('profit', value); // Update the form value if the input is valid } }} {...register("profit", { required: { value: true, message: "Enter profit amount", }, validate: { nonNegativeInteger: (value) => /^\d+$/.test(value) || "Profit must be a non-negative integer", }, })} /> {errors.profit && ( <span className="invalid-feedback">{errors.profit?.message}</span> )} </div>Key Considerations:
- Input Type: Using
type="text"allows you to intercept and validate input changes manually. - Regex Action:
/^\d*$/is used to allow only digits (0-9) without any decimal or negative signs. This keeps the value a whole number as input. - Validation: Alongside live changes, form validation is set up to ensure the condition is met if users bypass this (e.g., using copy-paste).
- Handling State Updates:
setValue('profit', value)directly updates the react-hook-form state whenever the user inputs a valid value, ensuring smooth form synchronization.
These adjustments ensure the input for profit is robust against any invalid characters while providing real-time user feedback.
- Input Type: Using
- User
profit fee will be as follows: (profit+contributionperhead)/(no of. participants -1)
- Assistant
To update your calculation of the contribution per head to include the new profit fee formula, you need to adjust the calculation logic. The formula for contribution per head should be
((goal + profit) / (participantSlots - 1)), assuming that the profit is being distributed among all participants except the creator. Here's how you can adjust the useEffect to reflect this change:useEffect(() => { if (goal && participantSlots) { const baseContribution = goal / participantSlots; // Base contribution const profitValue = parseFloat(profit) || 0; // Parse the profit value // Calculate the fee using the new formula const fee = participantSlots > 1 ? (profitValue + baseContribution * participantSlots) / (participantSlots - 1) : 0; // Avoid division by zero if there's only one participant // Format the output as desired const formattedContribution = `Contribution per head: ${( baseContribution + profitValue / participantSlots ).toFixed(2)} (+ ${fee.toFixed(2)}) USD`; setContributionPerHead(formattedContribution); // Update state with formatted contribution } else { setContributionPerHead(""); // Reset if no goal or slots } }, [goal, participantSlots, profit]);Adjustments Made:
- Fee Calculation: The
feeis calculated using the modified formula(profit + baseContribution * participantSlots) / (participantSlots - 1). This distributes the profit and the total goal evenly among the slots minus the creator. - Avoid Zero Division: Handles the possibility of zero or one participant slot, which would otherwise cause a division by zero error.
These adjustments ensure that the
contributionPerHeadstate reflects the updated fee calculation according to the specified requirements. - Fee Calculation: The
- User
what formula used here?
- Assistant
I apologize for the oversight. The formula discussed in my previous message was incorrect based on your requirements. Let's clarify the correct approach for calculating the contribution fee based on the provided context:
Given that the profit fee should be calculated as
(profit + contributionPerHead) / (number of participants - 1), wherecontributionPerHeadis(goal / number of participants), let's define the correct calculations:Here is the updated logic to calculate and display the contribution per head including the formula you provided:
useEffect(() => { if (goal && participantSlots) { const baseContribution = goal / participantSlots; // Base contribution per participant const profitValue = parseFloat(profit) || 0; // Parse the profit value // Calculate the fee considering (profit + contributionPerHead) divided by (participantSlots - 1) const fee = participantSlots > 1 ? (profitValue + baseContribution) / (participantSlots - 1) : 0; // Ensure no division by zero // Format the output with the base contribution and calculated fee const formattedContribution = `Contribution per head: ${baseContribution.toFixed( 2 )} (+ ${fee.toFixed(2)}) USD`; setContributionPerHead(formattedContribution); // Update state with formatted contribution } else { setContributionPerHead(""); // Reset if no goal or slots } }, [goal, participantSlots, profit]);Explanation:
- Base Contribution: Calculated as
goal / participantSlots, which gives the contribution from each participant assuming no profit. - Profit Fee Calculation:
(profitValue + baseContribution) / (participantSlots - 1), which spreads the profit and the additional amount from each participant (other than the creator) over the remaining slots. - Condition to Avoid Wrong Calculation: Checks for
participantSlots > 1to avoid potential division by zero, ensuring that calculations make sense only when there's more than one participant.
This corrected version should achieve the intended logic for distributing the profit over valid participant slots, adjusted to your scenario.
- Base Contribution: Calculated as
- User
doesnt feel right
- Assistant
Let me clarify the logic and ensure we calculate correctly based on your requirements.
You're aiming to distribute the profit fee alongside the base contribution among the participants, excluding the creator. Let's break it down:
-
Definitions:
goal: Total fundraising goal amount.profit: Intended profit amount.participantSlots: Total number of participant slots, including the creator.
-
Formulas:
-
Base Contribution (per participant): This is the amount needed without profit sharing: [ \text{baseContribution} = \frac{\text{goal}}{\text{participantSlots}} ]
-
Profit Fee (to be added per participant, excluding creator): [ \text{profitFee} = \frac{\text{profit}}{(\text{participantSlots} - 1)} ]
-
The total contribution per head (for each of the participants) would then be: [ \text{totalContribution} = \text{baseContribution} + \text{profitFee} ]
-
Let's implement this logic:
useEffect(() => { if (goal && participantSlots) { const baseContribution = goal / participantSlots; // Base contribution per participant const profitValue = parseFloat(profit) || 0; // Parse the profit value // Calculate the profit fee only among other participants excluding the creator const profitFee = participantSlots > 1 ? profitValue / (participantSlots - 1) : 0; // Prevent division by zero if only one participant // Calculate the total contribution per head including profit fee const totalContribution = baseContribution + profitFee; // Format the output with the base contribution and calculated profit fee const formattedContribution = `Contribution per head: ${totalContribution.toFixed( 2 )} USD`; setContributionPerHead(formattedContribution); // Update state with formatted contribution } else { setContributionPerHead(""); // Reset if no goal or slots } }, [goal, participantSlots, profit]);Explanation:
- Base Contribution: Divides the
goalamong all participants. - Profit Fee Distribution: Distributes the
profitsolely among the participants besides the creator, which is why it's divided by(participantSlots - 1). - Total Contribution Per Head: Sum the
baseContributionwith theprofitFee.
This logic distributes profit fairly among participants, ensuring that the creator's responsibilities are considered as per your rules.
-