-1

So I am passing in some data that i have saved in a state. I am then trying to pass that information as props on to another component. However, when I console.log it shows as undefined.

Here is the page i am passing information from:

import React, { useState } from 'react'
import { Link } from 'react-router-dom'
import axios from 'axios'
import IpContext from '../../IpContext'
import { useContext } from 'react';
import ReactDOM from 'react-dom';
import PostIssues from '../Trainee/PostIssues/PostIssues';

const LoginPage = props => {
const [userDetails, setuserDetails] = useState([]);
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [memberType, setMemberType] = useState("");


    const getLogin = (e) => {
        e.preventDefault();
        if (memberType === "trainee") {
            axios.get("http://" + ip + "/trainee/findByUsername/" + username)
                .then(response => {
                    setuserDetails(response.data);
                    console.log(userDetails)
                    console.log(response.data.id);
                }).catch(error => {
                    console.log(error)
                });
        } else {
            console.log("ignore")
        }
    }

    const validate = (e) => {
        if (userDetails.username === username && userDetails.password === password) {
            props.history.push("/postIssue");
            // userDetails[0].map((issue) => (
            <PostIssues
                // number={number}
                userDetails={userDetails}
            />
        }
        else {
            e.preventDefault();
            ReactDOM.render(<p style={{ color: "red" }}>Username/Password wrong</p>, document.getElementById('failed-message'));

        }
    }
return (
        <>

            <div className="loginDiv">
                <h1 className="loginHeading">Login</h1>
                <div>
                    <form className="ml-3" id="loginForm" onSubmit={validate}>
                        <input name="username" className="loginInput" type="text" id="username" placeholder="Enter your username" onChange={e => setUsername(e.target.value)} required></input> <br></br>
                        <input name="password" className="loginInput" type="password" id="password" placeholder="Enter your password" onChange={e => setPassword(e.target.value)} required></input> <br></br>
                        <select defaultValue="" name="traineeTrainer" onInput={e => setMemberType(e.target.value)} onChange={getLogin} >
                            <option value="" disabled hidden >Position</option>
                            <option value="trainer">Trainer</option>
                            <option value="trainee">Trainee</option>
                        </select>
                        <button className="btn btn-primary" id="loginButton" type="submit">Login</button>
                        <div>
                            <Link to="/createAccount">
                                <button style={{ backgroundColor: "darkred" }} className="btn btn-primary" id="signUpButton" type="button">Create an account</button>
                            </Link>
                        </div>
                    </form>
                </div>
            </div>

            {/* Login failed will appear here */}
            <div id="failed-message"></div>
        </>
    )
}

export default LoginPage


And this is where i want to receive information:

import React, {useState, useEffect} from 'react'
import axios from 'axios'
import Issue from '../../Trainer/Issue';
import IpContext from '../../../IpContext'
import { useContext } from 'react';

const PostIssues = props => {

    console.log(props.userDetails.username);

return(
)
}

export default PostIssues;

When I run this on the browser I get and error which says

"TypeError: Cannot read property 'username' of undefined".

Why is it undefined if i am passing it as props?

Thanks in advance!

  • You are not returning anything from the `LoginPage` component, so it won't render anything. – Rinkesh Golwala Dec 14 '20 at 21:41
  • I am calling a return statement, I have updated it now. Please check. Thank you! – Ambilli Radhakrishnan Dec 14 '20 at 21:43
  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Emile Bergeron Dec 14 '20 at 21:50
  • Also, you're initializing the state with an array `useState([])` then using it like it's a single object `userDetails.username`. – Emile Bergeron Dec 14 '20 at 21:52
  • And you're manipulating the DOM manually with `ReactDOM.render` in callbacks, which is an anti-pattern in React. It used to work like this with jQuery, but React is data driven. Update some state with the error and render once in the render cycle. – Emile Bergeron Dec 14 '20 at 21:53
  • you're not calling the validate function anywhere, you should check the function returns a React Node and be sure to call that function, in order to achieve what @RinkeshGolwala suggests – Fabio Lopez Dec 14 '20 at 21:53

1 Answers1

-1

You're not actually returning anything, even though you have a return() in there. Try return(null) and read this answer to see why.

Additionally, I would recommend you try to debug this by using the developer tools in your browser. The React tools are quite handy and they allow you to inspect props and state.

Try rendering props.userDetails.username in a <div> inside your return statement to see the page render the component.