I have 3 main files in my next.js Project. My settings are: no /src, yes App Router, yes Typescript, contains app/ folder. My main goal is to display some values that are updated through a form, in another page using React Contexts.
File 1 has location components/AddressForm.tsx. The main purpose is to provide a form and when submitted, update formData values that is defined inn File 2 (FormContext.tsx):
"use client"
import React, { useState } from 'react';
import { useFormContext, CheckoutData } from '../context/FormContext';
const AddressForm: React.FC = () => {
const { formData, setFormData } = useFormContext();
const [localFormData, setLocalFormData] = useState<CheckoutData>(formData);
// Update local form data on input change
const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const { id, value } = event.target;
setLocalFormData(prevData => ({
...prevData,
shippingAddress: {
...prevData.shippingAddress,
[id]: value
}
}));
};
// Update context with local form data on form submission
const handleFormSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setFormData(prevData => ({
...prevData,
shippingAddress: {
...localFormData.shippingAddress
}
}));
console.log('Form submitted with data:', localFormData);
};
Below this we have the return() with the form.
File 2 is context/FormContext.tsx. This file contains export interfaces and a FormProvider that defines const[formData, setFormData) which is planned to be updated in File 1:
"use client";
import React, { createContext, useContext, useState } from 'react';
export interface ShippingAddress {
name: string;
surname: string;
email: string;
gsmNumber: string;
address: string;
city: string;
state: string;
zip: string;
}
export interface BasketItems {
id: string;
name: string;
category1: string;
category2: string;
itemType: string;
price: number;
}
export interface CheckoutData {
shippingAddress: ShippingAddress;
billingAddress: ShippingAddress;
basketItems: BasketItems;
subtotal: number;
shipping: number;
discount: number;
total: number;
}
interface FormContextProps {
formData: CheckoutData;
setFormData: React.Dispatch<React.SetStateAction<CheckoutData>>;
}
const FormContext = createContext<FormContextProps | undefined>(undefined);
export const FormProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [formData, setFormData] = useState<CheckoutData>({
shippingAddress: {
name: '',
surname: '',
email: '',
gsmNumber: '',
address: '',
city: '',
state: '',
zip: ''
},
billingAddress: {
name: '',
surname: '',
email: '',
gsmNumber: '',
address: '',
city: '',
state: '',
zip: ''
},
basketItems: {
id: 'BI101',
name: 'Product Title 1',
category1: 'Collectibles',
category2: 'Accessories',
itemType: 'PHYSICAL',
price: 49.99
},
subtotal: 49.99,
shipping: 0,
discount: 0,
total: 49.99
});
return (
<FormContext.Provider value={{ formData, setFormData }}>
{children}
</FormContext.Provider>
);
};
export const useFormContext = () => {
const context = useContext(FormContext);
if (context === undefined) {
throw new Error('useFormContext must be used within a FormProvider');
}
return context;
};
File 3 only displays the data. I know for a fact that File 2 and File 3 is connected properly as the already defined subtotal and price values are perfectly diplayed in File 3. But the empty ones are never updated.
const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const { id, value } = event.target;
setLocalFormData(prevData => ({
...prevData,
shippingAddress: {
...prevData.shippingAddress,
[id]: value
}
}));
};
// Update context with local form data on form submission
const handleFormSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setFormData(prevData => ({
...prevData,
shippingAddress: {
...localFormData.shippingAddress
}
}));
console.log('Form submitted with data:', localFormData);
};
I am guessing the problem arises from the above section as there is no log:
Form submitted with data:', localFormData
when I submit the form through a type = submit button inside a tag in File 1. I am sure that the problem arises from a fault that disables the code to submit the form. Explaining the non-existing log, and the no display
mic_faraday is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.