0
votes

After authorization and redirect to /userProfile page I get error:

Uncaught (in promise) TypeError: Cannot read property 'name' of null.

I have <Page /> component.

Code of that:

const Page = () => {
    return (
        <div>
            <div style={{display: "flex", alignItems: "center", justifyContent: "space-between"}}>
                <h1>{`${userData.name} ${userData.surname}`}</h1>
                <button onClick={() => logout()} style={{display: "block"}}
                        className="btn btn-large ">
                    Выйти</button>
            </div>
        </div>
    );
};

It uses value from state named userData through useState hook

const [loading, setLoading] = useState(true);
const [userData, setUserData] = useState({name: "", surname: "", posts: [], email: "", password: ""});

I fetch data in useEffect hook

const request = useCallback(async (url, method = 'POST', body = null, headers = {}) => {
    setLoading(true)
    try {
        if (body) {
            body = JSON.stringify(body)
            headers['Content-Type'] = 'application/json'
        }
        const response = await fetch(url, {method, body, headers});
        const data = await response.json();
        setLoading(false);
        return data;
    } catch (e) {
        setLoading(false)
        throw e
    }
}, []);
useEffect(() => {
    const response = request("/api/user/getDataByUserId", "POST", {userId: userId});
    response.then(r => {
        setUserData(r.data);
    });
}, [request, userId]);

userId I get from AuthContext I have tried to solve this problem for two days, please HELP ME

2
What is the component in which you have your request method - Shubham Khatri
It seems <Page /> component does not have access to userData. Where do you use that component? Maybe you can try to pass userData through props. - norbitrial
I have completely found the solving. I needed to change h1 tag to {userData && <h1>{${userData.name} ${userData.surname}}</h1>} checking - Артём Лукичёв

2 Answers

0
votes

You need to check " setUserData(r.data) " inside useEffect, try doing console.log on r and r.data. The problem may be that r.data setting userData as null. If its coming null you can set default or invalid as per requirement.

Checking as "userData && {${userData.name} ${userData.surname}" will be a good practice and better way of doing it will be to make a function getFullNameMarkup and do the checks inside it.

0
votes

I changed h1 tag to {userData && <h1>{${userData.name} ${userData.surname}}</h1>} and it is working