-1

App.js

import { Component } from "react";
import "./App.css";
import checkUser from "./functions";
class App extends Component {
  constructor() {
    super();
    console.log(checkUser('',''));
  }

  render() {
    return (
      <>
        <h1 id="name">{this.user}</h1>
      </>
    );
  }
}
export default App;

functions.js

let checkUser = (username, password) => {
  let local_username = localStorage.getItem("username");
  let local_token = localStorage.getItem("token");
  let local_client_id = localStorage.getItem("client_id");
  if (username === "" && password === "") {
    fetch("/login?user=auth", {
      method: "POST",
      headers: {
        username: local_username,
        token: local_token,
        client_id: local_client_id,
      },
    })
      .then((data) => {
        data.json();
      })
      .then((data) => {
        return data
      });
  } else if (
    username !== null &&
    password !== null &&
    local_client_id === null
  ) {
    let res = fetch("/login?user=notloggedin", {
      method: "POST",
      headers: { username: username, password: password },
    })
      .then((res) => res.json())
      .then((data) => {
        if (data.status === true) {
          localStorage.setItem("username", username);
          localStorage.setItem("token", data.token);
          localStorage.setItem("client_id", data.client_id);
          return true;
        } else {
          return false;
        }
      });
  }
};

export default checkUser;

I am expecting checkUser function to log user name but it is logging undefined. It shows to request to server but not returning, I think that the problem is with the code in functions.js where I am returning something in a .then funtion.

  • 1
    Does this answer your question? [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Brian Thompson Jun 21 '21 at 13:18

1 Answers1

1

In the first .then() you forget to return data.json(). you can either return:

.then((data) => {
        return data.json();
      })


//or wrap it in brackets so it automatically returns:

.then((data) => (
        data.json();
      ))

//or make it one line:

.then((data) => data.json())
Mert Yurt
  • 80
  • 8