is there a way to fix this PropType error, it says I am passing fromData as String instead of object

36 Views Asked by At

This is an error I am getting from my webpage console

Warning: Failed prop type: Invalid prop formData of type string supplied to FirstSection, expected object. at FirstSection (http://localhost:5173/src/Components/applySections/FirstSection.jsx?t=1708303938624:14:25) at ApplicationForm (http://localhost:5173/src/Containers/ApplicationForm.jsx?t at Routes (http://localhost:5173/node_modules/.vite/deps/react-router-dom)

I am beginner at web-dev and I am getting the above error when I use formData in my FirstSection.jsx. So I am making an application form that is divided into different sections. I have implemented these different sections as different files e.g. firstSection.jsx, secondSection.jsx, thirdSection.jsx; in addition to this there is a parent component ApplicationForm.jsx where I combine all these sections to complete my application form. I have implemented these sections using formData so that it is easily rendered from the parent component.

below is my ApplicationForm.jsx which is the parent component:

// eslint-disable-next-line no-unused-vars
import React, { useState } from 'react';

import FirstSection from '../Components/applySections/FirstSection';
import SecondSection from '../Components/applySections/SecondSection';
import ThirdSection from '../Components/applySections/ThirdSection';
import FourthSection from '../Components/applySections/FourthSection';
import FifthSection from '../Components/applySections/FifthSection';
import SixthSection from '../Components/applySections/SixthSection';
import SeventhSection from '../Components/applySections/SeventhSection';
import './ApplicationForm.css';

const ApplicationForm = () => {
    const [formData, setFormData] = useState({
        FirstSection: {},
        SecondSection: {},
        ThirdSection: {},
        FourthSection: {},
        FifthSection: {},
        SixthSection: {},
        SeventhSection: {},
    });

    const [showReview, setShowReview] = useState(false);

    const handleFormChange = (section, data) => {
        setFormData((prevData) => ({
          ...prevData,
          [section]: data,
        }));
    };

    const handleReview = () => {
        setShowReview(true);
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        try{
            await fetch('localhost:5000/applications', {
                method: 'POST', 
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(formData),
            })
            console.log('Submitting Form');
            alert("Your application has been submitted successfully!");
        } catch(err){
            console.log(err);
            alert("An error occurred while submitting your application. Please try again later.");
        }
    };

    return (
        <div className='application-form-container'>
            <FirstSection formData={formData.FirstSection} onFormChange={(data) => handleFormChange("FirstSection", data)} />
            <SecondSection formData={formData.SecondSection} onFormChange={(data) => handleFormChange("SecondSection", data)} />
            <ThirdSection formData={formData.ThirdSection} onFormChange={(data) => handleFormChange("ThirdSection", data)} />
            <FourthSection formData={formData.FourthSection} onFormChange={(data) => handleFormChange("FourthSection", data)} />
            <FifthSection formData={formData.FifthSection} onFormChange={(data) => handleFormChange("FifthSection", data)} />
            <SixthSection formData={formData.SixthSection} onFormChange={(data) => handleFormChange("SixthSection", data)} />
            <SeventhSection formData={formData.SeventhSection} onFormChange={(data) => handleFormChange("SeventhSection", data)} />

            <button onClick={handleReview}>Review</button>
            <button onClick={handleSubmit}>Submit</button>

            {showReview && (
                <div className="review-modal">
                    <h2>Review Your Information</h2>
                    {/* Display a summary of entered information */}
                    {/* You can format and display the information as needed */}
                    <pre>{JSON.stringify(formData, null, 2)}</pre>
                    <button onClick={() => setShowReview(false)}>Close</button>
                </div>
            )}
        </div>
    );

    
};

export default ApplicationForm;

and this is my FirstSection.jsx:

import React from 'react';
import PropTypes from 'prop-types';
import './FirstSection.css'

const FirstSection = ({ formData = {}, onFormChange }) => {
  const updateFormData = (field, value) => {
    onFormChange(field, value);
  };

so the question is what does the above error mean and how can I fix it?

I have tried writing inline code that makes sure the formData rendered from the parent component is indeed an object but the error still remains.

1

There are 1 best solutions below

0
Kyle Xyian Dilbeck On

Update the FirstSection component to handle cases where formData is not an object. One way to do this is to check if formData is an object before using it. If it's not an object, you can set it to an empty object. Here's an updated version of your FirstSection component:

import React from 'react';
import PropTypes from 'prop-types';
import './FirstSection.css';

const FirstSection = ({ formData, onFormChange }) => {
  const updateFormData = (field, value) => {
    onFormChange(field, value);
  };

  // Check if formData is an object, otherwise set it to an empty object
  if (typeof formData !== 'object' || formData === null) {
    formData = {};
  }

  // Rest of your component code
};

FirstSection.propTypes = {
  formData: PropTypes.object,
  onFormChange: PropTypes.func.isRequired,
};

export default FirstSection;

Explanation: Adding the check for typeof formData !== 'object' || formData === null and setting formData to an empty object if it's not an object, you should be able to resolve the warning.

This ensures that formData is always treated as an object, even if it's not provided correctly from the parent component.


PS: If this answers your question, remember to mark it as answered and/or upvote if you liked it! :-) https://stackoverflow.com/help/someone-answers