Home
Support Forums

Append external data to the form in React

I am using Netlify forms and I would like to append to my form shopping cart - so together with the form the shopping cart will be send as well.

So far I am receiving data only from the form and can’t reach the shopping card.

This is html for the form:

 <form
      className="myform"
      onSubmit={handleSubmit}
      data-netlify="true"
      name="landing-form"
      data-netlify-recaptcha="true"
      method="post"
 > 
<input
      type="text"
      placeholder="Your Name"
      name="name"
      required
      value={name}
      onChange={(e) => setName(e.target.value)}
      ></input>
<input
       type="email"
       placeholder="Your E-Mail"
       name="email"
       required
       value={email}
       onChange={(e) =>setEmail(e.target.value)}
      ></input>                                    
<button type="submit">Send</button>
</form>

And JS code that works only for input fields, but not for updatedCart

    const [name, setName] = useState('');
    const [email, setEmail] = useState('');
    const [message, setMessage] = useState('');
    const history = useHistory();

    function emailIsValid(email) {
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    }
    const handleSubmit = (e) => {
        e.preventDefault();

        if (name && emailIsValid(email) && message && updatedCart) {
            fetch('/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: encode({
                    'form-name': 'landing-form',
                    name: name.trim(),
                    email: email,
                    message: message.trim(),
                    updatedCart: updatedCart,
                }),
            })
                .then((res) => {
                    redirectAfterSubmission();
                })
                .catch((error) => alert(error));
        }
    };

    const redirectAfterSubmission = () => {
        setTimeout(() => {
            history.push('/thank-you');
        }, 1500);
    };

Obviously putting my updatedCart in JS is not enough, but I am not sure how else to handle it, since the shopping cart is not an input.

My cart data:

const addToCart = (item) => {
        setCart([...cart, item]);
        setUpdatedCart([
            ...updatedCart,
            `Package: ${item.name}`,
            `Chair: ${item.chair.name}`,
            `Desk: ${item.desk.name}`,
            `Plan: ${plan}`,
            `Number of months: ${months}`,
        ]);
    };

HI @anwarjutt7690

This is because Netlify reads the form from your page during build time to determine the fields for processing so adding extra fields at form submission time is not possible.

By seconding what @coelmay said, the only option for you is to use Serverless Functions, or some third-party form solution.