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(res.data))
    .catch(err => console.log(err));
},[filename]);

return(
    <div className="__te_onlineBanking__Form">
        <form>
            {gotData.formInputFields.map(elem => {return(
            <span>
                <label htmlFor= {elem.id}>{elem.labelText}</label>
                <input type= {elem.inputType} required id = {elem.id} placeholder = {elem.placeholder} name = {elem.name}/>
            </span>)
            })}
        </form>
        {console.log(gotData.formInputFields)}
        <button onClick = {close}>Submit</button>
    </div>
)

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(res.data), FYI, res.data is an object with some properties and an array for the form input field names. So, when I try to write, gotData.formInputFields.map(), I get an error saying cannot read property, map of undefined. However when I set setData(res.data.formInputFields), and then call gotData.map(), 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(res.data) and call the map with gotData.formInputFields.map(). Please help.

Answer

If I am not confused, your problem is that gotData is an object or JSON, so the first iteration is gotData.formInputFields.map 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 {gotData.formInputFields.map(elem => {return( to {gotData?.formInputFields?.map(elem => {return( or {gotData && gotData.formInputFields && gotData.formInputFields.map(elem => {return(

Leave a Reply

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