Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

Cannot read properties of 'undefined': 'props'

ppowell777

Well-Known Coder
I am trying to write a very simple React standalone function that will take a URL as a parameter and return the fetched HTML as a result to the parent component.

Here is my code:

JavaScript:
import { useEffect, useState } from 'react';

const GetData = ({ props }) => {
    const [html, setHtml] = useState('');
    const [loading, setLoading] = useState(true);

    useEffect((props) => {
        console.log(typeof props);  // "undefined" why?
        const controller = new AbortController();
        const timeout = setTimeout(() => {
            controller.abort();
        }, 5000);
        fetch(props.url, {
            signal: controller.signal
        })
            .then(response => {
                clearTimeout(timeout);
                if (response.ok && response.status === 200) {
                    return response.text();
                } else if (response.status >= 400) {
                    return Promise.reject(response.statusText);
                }
            })
            .then(async html => {
                setHtml(await html);
                setLoading(false);
            })
            .catch(error => {
                console.error(error);
            });
    });

    if (loading) {
        return '';
    } else {
        return html;
    }
}

export default GetData;

And here is the Header.js that calls it (among other React components that will also call it):

JavaScript:
import React from 'react';
import GetData from './get_data';
import headerPng from './images/header.png';

const Header = () => {

    const myUrl = 'http://localhost/test.php';

    return (
        <header id="fvap_header" className="usa-header">
            <div><GetData url={ myUrl } /></div>
             This is my header
        </header>
   );
};

export default Header;

I am passing the URL as I understand how to pass a parameter to a React component, and yet I constantly get the error:
Cannot read properties of undefined: 'props"

I have no idea how to fix this issue; this after hours of Google searching to no avail. Please help.

Thanks
 
Hey mate,

You’re almost there — it’s just a small mix-up with how you're handling props.

In your GetData component, you're doing:

Code:
const GetData = ({ props }) =&gt; {<br>
But when you call it like this:

Code:
&lt;GetData url={myUrl} /&gt;<br>
…it’s passing url directly — not an object called props. So inside your component, props is undefined, which is why you're getting that error.

Just change your component to this:

Code:
const GetData = ({ url }) =&gt; {<br>
And then update your useEffect to this:

Code:
useEffect(() => {
    const controller = new AbortController();
    const timeout = setTimeout(() => {
        controller.abort();
    }, 5000);

    fetch(url, { signal: controller.signal })
        .then(response => {
            clearTimeout(timeout);
            if (response.ok) return response.text();
            return Promise.reject(response.statusText);
        })
        .then(text => {
            setHtml(text);
            setLoading(false);
        })
        .catch(error => {
            console.error(error);
            setLoading(false);
        });

    return () => controller.abort();
}, [url]);

Also heads up — components don’t return raw data like functions. If you want to return the HTML string to the parent, you’ll need to turn this into a custom hook, or just render it directly inside GetData using dangerouslySetInnerHTML.

Let me know which direction you're going and I’ll chuck you a quick example.
 
Sorry for getting back so late.

My friend helped me solve it by converting the component into a pure React non-component function that uses React Hooks:

JavaScript:
import { useEffect, useState } from 'react';

// React function non-component due to naming convention
export const useGetData = ({ url }) => {
    const [html, setHtml] = useState('');
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const controller = new AbortController();
        const timeout = setTimeout(() => {
            controller.abort();
        }, 5000);
        fetch(url, {
            signal: controller.signal
        })
        .then(response => {
                clearTimeout(timeout);
                if (response.ok && response.status === 200) {
                    return response.text();
                } else if (response.status >= 400) {
                    return Promise.reject(response.statusText);
                }
            })
        .then(async html => {
                setHtml(await html);
                setLoading(false);
            })
        .catch(error => {
                console.error(error);
         });
    });

    if (loading) {
        return '';
    } else {
        return html;
    }
}

And calling it like this:

JavaScript:
return (
  <div>{ useGetData({url: myUrl}) }</div>
)
 
Back
Top Bottom