Cannot fetch an array within an object with axios call

see the code below:

//useState to store the file data:
const [gotData, setData] = useState({});

useEffect(() => {
    //calling the file's data. 
    instance(`/${filename.replace(" ", "%20")}`)
    .then(res => setData(
    .catch(err => console.log(err));

    <div className="__te_onlineBanking__Form">
            { => {return(
                <label htmlFor= {}>{elem.labelText}</label>
                <input type= {elem.inputType} required id = {} placeholder = {elem.placeholder} name = {}/>
        <button onClick = {close}>Submit</button>

The problem occurs in the map function. Right now in the above code, I am storing the data directly into the state variable with setData(, FYI, is an object with some properties and an array for the form input field names. So, when I try to write,, I get an error saying cannot read property, map of undefined. However when I set setData(, and then call, the problem is solved. But, I dont want to use two separate useStates for storing the form input field data and other information that I might need. I just want to setData( and call the map with Please help.


If I am not confused, your problem is that gotData is an object or JSON, so the first iteration is but formInputFields do not exist, as you wrote useState({}) so the initial state is gotData = {}.

Remember that you will have data on gotData once you have a response on your AJAX call, and that will take more time than the first render.

I recommend you to write useState({ formInputFields: [] }) or change your return from { => {return( to {gotData?.formInputFields?.map(elem => {return( or {gotData && gotData.formInputFields && => {return(

Leave a Reply

Your email address will not be published. Required fields are marked *