3

I am getting, cannot read data of undefined error. All I am doing here is trying to pass res.data.photo to useContext(UserLoginContext) from the Login.js. I need to display the image in Navigation.js src={dataImage},{loginImage}

Unhandled Rejection (TypeError): Cannot read property 'data' of undefined

Login.js

const {loginPhoto, setLoginPhoto} = useContext(UserLoginContext);

  const onSubmit = () => {
    const fetchData = async () => {
      try {
        const res = await axios.post('http://localhost:8000/service/login', { email, password });
        console.log("Front End success message:" + res.data.success);
        if (res.data.success) {
          setHelperText("Login successfully");
          setLoginPhoto(res.data.photo);
          setValue(res.data.privilege);
          localStorage.setItem('Privilege', res.data.privilege);
          localStorage.setItem('loginEmail', email);
          history.push('/')
          window.location.reload(true)
        }
        else {
          const failMessage = res.data.fail;
          setHelperText(failMessage);
        }
      } catch (e) {
        console.log(e.response.data);
        setHelperText(e.response.data.fail);
      }
    }
    fetchData();
  };

UserLoginProvider.js

import UserLoginContext from '../context';

const UserLoginProvider = ({children}) => {

    const [loginPhoto, setLoginPhoto] = useState({ photo:''});

     const value = useMemo(() => ({
        loginPhoto, setLoginPhoto
    }), [loginPhoto]);


    return (
       <UserLoginContext.Provider value={value}>
           {children}
       </UserLoginContext.Provider>
    )   
}
export default UserLoginProvider;

context.js

import React from 'react';

export default React.createContext();

Navigation.js

import UserProfileContext from '../context';
import UserLoginContext from '../context';

const Navigation = () => {

    const history = useHistory();
    const [imageSrc, setImgSrc] = useState(null);
    const [loginImgSrc, setLoginImgSrc] = useState(null);
    const { picture } = useContext(UserProfileContext);
    const { loginPhoto } = useContext(UserLoginContext);

    useEffect(() => {
        if (picture.photo) {
            const reader = new FileReader();
            reader.addEventListener('load', () => {
                setImgSrc(reader.result);
                localStorage.setItem("imgData", reader.result);
            });
            reader.readAsDataURL(picture.photo);
        }
    }, [picture.photo])

       var dataImage = localStorage.getItem('imgData');

       useEffect(() => {
        if (loginPhoto.photo) {
            const reader = new FileReader();
            reader.addEventListener('load', () => {
                setLoginImgSrc(reader.result);
                localStorage.setItem("loginImgData", reader.result);
            });
            reader.readAsDataURL(loginPhoto.photo);
        }
    }, [loginPhoto.photo])

    var loginImage = localStorage.getItem('loginImgData');


    return localStorage.getItem('loginEmail') &&
        <div className="App">
            <div className="wrapper">
                <div id="wrap">
                    <nav className="siteNavigation_nav_links">
                        <div className="clubLogo landing" style={divStyle}><b>Southside Soccer</b></div>
                        <NavLink className="mobile_register_link" to="/">Home</NavLink>
                        <NavLink className="mobile_register_link" to="/profile">Profile</NavLink>
                        <NavLink className="mobile_login_link" to="/login" onClick={logout}>Logout</NavLink>
                        <NavLink className="mobile_login_link" to='/aboutus'>About us</NavLink>
                        <span className="image_login_link"><img className="nav_profile" src={dataImage},{loginImage}></img></span>
                    </nav>
                </div>
            </div>
        </div>
}

export default Navigation;
soccerway
  • 10,371
  • 19
  • 67
  • 132
  • first, check ```res``` value, is ```res``` undefined? – MUHAMMAD ILYAS Jun 17 '20 at 23:51
  • Sorry , `res` is not undefined, because if I comment `setLoginPhoto(res.data.photo);` in res.data.success it allows me to login ... – soccerway Jun 17 '20 at 23:56
  • so that means its a magic, ```if (res.data.success)``` here res defined and working but after condition true the ```res``` goes undefined as you post said ```Unhandled Rejection (TypeError): Cannot read property 'data' of undefined``` – MUHAMMAD ILYAS Jun 18 '20 at 00:05
  • Yes as soon as I comment this line `setLoginPhoto(res.data.photo);` it allows me to login, I strongly feel if I am correct at this line >>.. `const {loginPhoto, setLoginPhoto} = useContext(UserLoginContext);` – soccerway Jun 18 '20 at 00:09
  • ```setLoginPhoto(res.data.photo)``` to chek this manually assign a the value – MUHAMMAD ILYAS Jun 18 '20 at 00:10
  • I am getting console.log("My Photo Data:" + res.data.photo); >> Console My Photo Data: images\photo-1592376542020.JPG – soccerway Jun 18 '20 at 00:50
  • what happens if you manually assign this value like ```setLoginPhoto("images\photo-1592376542020.JPG")``` – MUHAMMAD ILYAS Jun 18 '20 at 01:06
  • Unhandled rejection (Type Error) ..cannot read property data of undefined – soccerway Jun 18 '20 at 01:10
  • then its problem with your ```UserLoginContext``` shows the code for that – MUHAMMAD ILYAS Jun 18 '20 at 01:14
  • Added `context.js` to question, The `UserLoginContext ` is import from `../context` – soccerway Jun 18 '20 at 01:21

1 Answers1

0

It's a really bad idea to share the exact same context between two different Provider/consumer patterns:

import UserProfileContext from '../context';
import UserLoginContext from '../context';

This needs to be two separate contexts:

In context.js:

// context.js
import React from 'react';

export const UserProfileContext = React.createContext();
export const UserLoginContext = React.createContext();

In Navigation.js:

// Navigation.js
import { UserProfileContext, UserLoginContext } from '../context';

If they actually are supposed to be the same context, then just pick one name, use that, and avoid duplicates. Anything else is confusing and possible error-breaking.

jered
  • 11,220
  • 2
  • 23
  • 34
  • Now Attempted import error: '../context' does not contain a default export (imported as 'UserProfileContext').imported in another place called Profile..but giving error.. I have `import UserProfileContext from '../context';` – soccerway Jun 18 '20 at 01:53
  • How can I change the import according to suggested way there in Profile ? – soccerway Jun 18 '20 at 01:53
  • @soccerway it's right there in the answer... `import { UserProfileContext, UserLoginContext } from '../context';` – jered Jun 18 '20 at 01:57
  • ```import { UserProfileContext, UserLoginContext } from '../context';``` he is not exporting const so this is not a valid statement – MUHAMMAD ILYAS Jun 18 '20 at 02:07
  • @MUHAMMADILYAS guys it's right there in my answer. You need to make changes in two files. Export two separate contexts as `const` from the contexts.js file, and import them differently in Navigation.js... – jered Jun 18 '20 at 02:09
  • Thank you, I have done that ..now i am getting `react-dom.development.js:22665 Uncaught TypeError: Cannot destructure property 'loginPhoto' of 'Object(...)(...)' as it is undefined.` – soccerway Jun 18 '20 at 02:15
  • I could see console.log("My Photo Data:" + res.data.photo); >>> My Photo Data: images\photo-1592376542020.JPG – soccerway Jun 18 '20 at 02:16
  • @soccerway that is probably because you are not properly providing a value for that context in the component's parents. Remember that the value of `useContext(whatever)` is going to be `undefined` if the context `whatever` never had a context Provider set that value. – jered Jun 18 '20 at 02:18
  • Inside the `UserLoginProvider` I have set like this way as mentioned in my question ... `const [loginPhoto, setLoginPhoto] = useState({ photo:''}); const value = useMemo(() => ({ loginPhoto, setLoginPhoto }), [loginPhoto]); return ( {children} ) ` – soccerway Jun 18 '20 at 02:21