Home > Mobile >  Page not changing onClick using useNavigate in React?
Page not changing onClick using useNavigate in React?

Time:04-16

I have a very basic UI for a login page: enter image description here

Upon clicking the LOGIN button, the following methods gets called:

async function loginPatient(){
       let item ={username:userName, password};
       let result = await fetch("http://localhost:8000/users/login",{
           method:'POST',
           headers:{
               "Content-Type":"application/json",
               "Accept":"application/json"
           },
           body: JSON.stringify(item)
       });
        alert(result);
        alert("breakpoint")
       result = await result.json();
       localStorage.setItem("user-info",JSON.stringify(result));
       nav('/patient')
   }

At this point I simply want it to change the page when the button is clicked. My API returns the following information from the database: enter image description here

To test I did console.log("hello world") in the first line of the function and it works However, If I run console.log("hello world") after the let result = await fetch(...) part it does not work. How can I test this to see why it's not working ?

Here are the errors from the console: enter image description here

I did not write the API and do not know how Node works yet, I am just doing the front end for this

CodePudding user response:

First initialize you navigation variable as follows

const navigate =useNavigate()

then navigate to you specific route by returning you navigation variable as follows.

return navigation("/");

Happy Coding!

CodePudding user response:

The issue is code is never reaching after fetch line, basically request is failing, the error on console is saying the due to CORS issue, the request failed, and in your loginPatient function, you have not handled the failed case, if you just wrap your fetch call inside try/catch block, you will see your code will fall into fail block, as api failed.

You need to enable CORS on your server or backend, Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.

You can read more about cors at: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Looks like your client is on some other domain or port(if your are developing locally) than your server. You need to enable CORS permission for your client url.

And if you are using express for your backend, you can check the following url to enable cors. https://expressjs.com/en/resources/middleware/cors.html

And last thing why Postman is getting success response, because it is by passing this cors check, as Postman is making request from it's server to your direct server instead of browser.

  • Related