I believe it's a simple logic, but as I'm still learning I'm having a bit of difficulty implementing it.
On the login page of my project, I get the data of who logged in after a post request. and in the user I have the field "type". There are 2 types of users only.
I want that, if the user has type A, he is redirected to the "home" page, if he is type B, he goes to the "main" page. If you don't have a type value defined yet, go to the "usertype" page.
I wrote this logic here but it's not working. can anybody help me?
heres my code
async function onFinish(values) {
let axiosConfig = {
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "*",
},
};
Axios.post(
` /login`,
{
email: values.email,
senha: values.password,
},
axiosConfig
)
.then((resp) => {
var name = resp?.data[0]?.prinom;
var userId = resp?.data[0]?.id;
var prodUser = resp?.data[0];
localStorage.setItem("prodUser", JSON.stringify(prodUser));
//here's the part i need help
if (!resp?.data[0]?.tipo) history.push("/tipodeusuario");
resp?.data[0]?.tipo === "pac" ? history.push("/homepac") : history.push("/home");
})
After you find the user type (i.e., A or B)
you can simply assign a new url to window.location
Here's some pseudo code
function getUserType(AorB){
//Get user type
return AorB;
}
//Store urls in a variable
let url = (getUserType('A') == 'A')? './UrlForUserTypeA':'./UrlForUserTypeB';
//Redirect
console.log('Redirecting...');
window.location = url;
Hope that's what you needed
First of all you need to store your response in a variable to have a readable code so :
let apiResp = respoone.data.tipo;
if (apiResp === A){
history.push('/HomePage')
}if(apiResp === B) {
history.push('/MainPAge')
}else {
history.push('/userType')
}
You can also use "Switch Case" Approach.
Or Conditional (ternary) operator which I don't recommend because it makes your code less readable.
useHistory has changed in react-router v6. now we use useNavigate.
if (apiResp === A){
navigate('/HomePage');
}if(apiResp === B) {
navigate('/MainPage');
}else {
navigate('/userType');
}
thanks @Amin Arshadinia :)