I have an api.js file with the following function:
export const login = (loginUserName, loginPassword, setUser) => {
axios({
method: 'post',
data: {
username: loginUserName,
password: loginPassword
},
withCredentials: true,
url: '...........'
}).then(async (res) => {
if (res.data.loggedIn === true) setUser(loginUserName);
});
};
My useState hooks looks the following:
const [ user, setUser ] = useState({});
I was wondering, instead of sending the setUser function from my Login component like I do:
login(userName,password,setUser);
which is in another file, how can I do it from outside of the function like the following:
setUser(login(userName,password));
So in case the function did retrieve the information I wanted it'll return it (in this case the username), and in case not it will set the user as undefined or something.
I tried using
export const login = (loginUserName, loginPassword) => {
axios({
method: 'post',
data: {
username: loginUserName,
password: loginPassword
},
withCredentials: true,
url: '............'
}).then(async (res) => {
if (res.data.loggedIn === true) return loginUserName;
});
};
But I had some struggling with the async function. It seems like it wont return that information for some reason. if I had to guess it returns it only for the axios function or something.. How do I get the effect I am looking for and what's the best practice? Is sending the "setUser" function considered a good practice or is it better trying to get rid of it?