简体   繁体   中英

Issues with response from express file to front end (React)

Hi I am making a basic questionnaire within a react full stack website I am creating using React,express and sql.

At the moment all I am trying to do is return a error message from react and get my front end to dispaly it .

This is my express endpoint.

app.post("/post-question-answers", async (req, res) => {
  console.log("!called");
  try {
    await sql.connect(config);

    // create Request object

    let selectedWorkstation = req.body.selectedWorkstation;

    var request = new sql.Request();
    request.input(`SelectedWorkstation`, sql.NVarChar, selectedWorkstation);
    let existingWSA = await request.execute("dbo.CheckIfWSAExists");
    if (!existingWSA.recordset.length) {
      console.info("hello from first if");
      let user = req.body.user;
      let results = req.body.results;
      let completeToken = req.body.completeToken;
      let date = req.body.date;

      let questions = [];
      let answers = [];
      // let emails = [];
      let questionIds = [];
      let suggestedSoloutions = [];

      results.forEach(element => answers.push(element.answer));
      results.forEach(element => questions.push(element.question));
      // results.forEach(element => emails.push(element.email));
      results.forEach(element => questionIds.push(element.questionId));
      results.forEach(element =>
        suggestedSoloutions.push(element.suggestedSoloution)
      );

      var request = new sql.Request();
      request.input(`QuestionStatus`, sql.NVarChar, completeToken);
      request.input(`Date`, sql.NVarChar, date);
      request.input(`Email`, sql.NVarChar, user);
      request.input(`SelectedWorkstation`, sql.NVarChar, selectedWorkstation);
      let result = await request.execute("dbo.AddQuestionResponseHeader");

      console.log("HERE");
      console.log(result);
      if (result.hasOwnProperty("recordset") && result.recordset.length) {
        var recordsetRow = result.recordset[0];

        if (recordsetRow.hasOwnProperty("createdId")) {
          var id = recordsetRow.createdId;
          console.log(id);

          for (var i = 0; i < results.length; i++) {
            var request = new sql.Request();
            let answer = answers[i];
            let question = questions[i];
            // let email = emails[i];
            let questionId = questionIds[i];
            let soloution = suggestedSoloutions[i];

            request.input(`WSAId`, sql.Int, id);
            request.input(`Question`, sql.NVarChar, question);
            request.input(`Answer`, sql.NVarChar, answer);
            request.input(`Email`, sql.NVarChar, user);
            request.input(`QuestionId`, sql.NVarChar, questionId);
            // request.input(`CompleteToken`, sql.NVarChar, completeToken);
            request.input(
              `SelectedWorkstation`,
              sql.NVarChar,
              selectedWorkstation
            );
            request.input(`SuggestedSoloution`, sql.NVarChar, soloution);

            request.execute("dbo.SubmitQuestionResponses", function(
              err,
              recordset
            ) {
              if (err) console.log(err);
            });
          }
        } else {
          console.log("unexpected result format");
        }
      } else {
        console.log("No results found");
      }
    } else {
// HERE is what I am asking about
      console.info("This account exists");
      let errorMessage =
        "This Workstation currently has an assessment in progress";
      res.status(409).json({
        errorMessage: errorMessage
      });
    }
  } catch (e) {
    console.log(e);
  }
});

So this is working fine the response is within the final else is (where the comment is).This is reached when a workstation exists and works fine.I then try to pass back this error message within this else.

This is my fetch statement within my submit answers function

 submitAnswers() {
    let selectedWorkstation = window.localStorage.getItem("Workstation");
    let user = window.localStorage.getItem("User");

    let completeToken = "";
    let declinedCounter = 0;

    if (questionCounter == this.state.questions.length) {
      var today = new Date(),
        date = `${today.getUTCFullYear()}-${today.getUTCMonth() +
          1}-${today.getUTCDate()} ${today.getHours()}:${today.getMinutes()}:${today.getSeconds()}.${today.getMilliseconds()} `;

      for (var i = 0; i < results.length; i++) {
        if (results[i].answer == "P") {
          declinedCounter++;
        } else {
        }
      }

      if (declinedCounter > 0) {
        completeToken = "In Progress";
      } else if (declinedCounter <= 0) {
        completeToken = "Complete";
      }

      console.log(completeToken);
      const data = {
        completeToken,
        results,
        selectedWorkstation,
        date,
        user: user
      };

      fetch("/post-question-answers/", {
        method: "POST", // or 'PUT'
        headers: {
          Accept: "application/json,",
          "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
      }).then(({ errorMessage }) => {
        this.setState({ errorMessage: errorMessage });
        alert(this.setState.errorMessage);


// Here is what I am referencing

        if (this.setState.errorMessage.length > 2) {
          alert("test1");
        } else if (this.setState.errorMessage.length < 2) {
          alert("test2");
        }
      });

      window.location.href = "http://localhost:3000/completed-assessment";
    } else {
      alert("Please enter all of The questions");
    }
  }

This error message has worked once or twice on first use. Then it is either undefined or does not alert the user anything.

I am searching for the reason that this is not displayed every time a workstation exists. As it is usually undefined or will not show at all.

Any help at all would be greatly appreciated.

You are incorrectly accessing the state variables. State variables are accessed using this.state not this.setState .

Also, put the alert in the callback of setState. setState is asynchronous, so by the time you use this.state.errorMessage inside alert, it may have not been updated yet. So, instead try this:

this.setState({errorMessage}, () => {alert(this.state.errorMessage)})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM