filifunk
filifunk

Reputation: 837

why am I getting a `destructured parameter is undefined` when the console.log tells me that those are defined?

This is my code that I am using to try and log in to my react/flask app:

const logitin = ({username, password}) => {
            console.log('this place',username, password)
            function loginuser({username, password}) {
            fetch(`http://localhost:5000/userlookup`, {
                'method':'POST',
                mode: 'cors',
                headers: {
            'Content-Type':'application/json'
                },
                body: JSON.stringify(username, password)
            })
            .catch(error => console.log('error time!', username, password))
            }
            return (<div>{loginuser()}</div>)
            }
        console.log('that place', username, password)
        logitin({username, password})

the line that says console.log('this place', username, password) and console.log('that place', username, password) tells me exactly what I expect the username and password are.

This is the error I'm getting: TypeError: (destructured parameter) is undefined

Upvotes: 4

Views: 4775

Answers (1)

coagmano
coagmano

Reputation: 5671

This function declaration here:

    function loginuser({username, password}) {

creates a new scope for the variables username and password, and destructures them from the passed in argument.

That function is called here:

    return (<div>{loginuser()}</div>)

Without any argument. This means that login user will start by attempting to do:

  { username, password } = undefined

Which is the type error that you are recieving.

Beyond that, you shouldn't be calling functions in JSX like this.


Solution

Either make this an ordinary function:

const logitin = async ({ username, password }) => {
  try {
    await fetch(`http://localhost:5000/userlookup`, {
      method: "POST",
      mode: "cors",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(username, password),
    });
    return true;
  } catch (error) {
    console.log("error time!", username, password);
    return false;
  }
};

This will return true/false depending on if the request succeeded.

Or if this is a react component, use a useEffect:

const logitin = ({ username, password }) => {
  useEffect(() => {
    function loginuser() {
      fetch(`http://localhost:5000/userlookup`, {
        method: "POST",
        mode: "cors",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(username, password),
      })
        .then(() => {
          // update global state, redirect somewhere, idk
        })
        .catch((error) => console.log("error time!", username, password));
    }
    loginuser();
  }, []);
  return <div>Logging in...</div>
};

Upvotes: 5

Related Questions