Home > Mobile >  How to check states after sending request in server?
How to check states after sending request in server?

Time:09-21

I am trying to check states after sending requests to the server by using axios. I designed the server that if you submitted the form with an empty input, you will get an error. If you can see in the code, I have tried to check the states in finally block but it is not working properly. Like when I submitted the form initially with no inputs, the console log displays no errors and when I try to submit the form with the inputs, it doesn't display anything in the console. I just want to check if there is an error with the request because I want to run a function between them.

The server I used is live and running and you can get the data/submitted form by changing the URL into /getUser

Code here: https://codesandbox.io/s/quizzical-danny-dv1l7?file=/src/App.js

CodePudding user response:

It doesnt works like that.

const [error, setError] = useState("");

error is the initial value (empty string). In dont realy knows how useState is working but, error is a string so it s a value, not a reference. There is no way this variable get updated it the finaly block.

CodePudding user response:

The simple answer is you are setting your state inside the function and then trying to read it as your "current state". Try this instead...

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      await axios.post("https://testing-name-app.herokuapp.com/create", {
        first,
        last
      });
    } catch (error) {
      console.log("error found");
     return setError(error.response.data.errorMessage);
    } 
    // be CAREFUL with this pattern! This just means the request came back
    // with no errors, but there may be a message from your call that 
    // contained an error from your db/server etc  
    return console.log("no errors");
  };

And here's a way to quickly see what's going on in your call...

  const handleSubmit = async (e) => {
    e.preventDefault();

    let res
    try {
      res = await axios.post("https://testing-name-app.herokuapp.com/create", {
        first,
        last
      });
    } catch (error) {
      res = error
      console.log("error found");
      setError(error.response.data.errorMessage);
    } 
    finally {console.log('res: ', res)} 
  };
  • Related