Is this a sound implementation of a signup function? - javascript

Are the async and await in the right places given this arrow function.
What about the const at the start? Is that okay?
Flow of the function as well as it's compartmentalization. (I put it in a different file, and upon submitting a form in my signup component, it will be called)
Should I save the results of this function in a variable in my signup component and then evaluate it there to see what to do next?
Helpful info:
I am doing form validation with Yup prior to submitting the form. So all that is being returned from the server is "email taken" or "successful registration".
Thank you!
/*
File: src/utils/authentication.js
Author: jreyes
Date: 01-26-2021
*/
/** Register new user */
const signupAuth = async () => {
await fetch('http://localhost:8080/signup', {
method: 'POST',
mode: 'cors',
credentials: 'omit',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email,
password,
firstname,
lastname
})
})
.then(response => {
if (!response.ok) {
throw new Error('Please check your network.');
}
return response.json();
})
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
};
export { signupAuth };

you should try to do something like that:
export const signupAuth = (email, password, firstname, lastname) => {
return fetch('http://localhost:8080/signup', {
method: 'POST',
mode: 'cors',
credentials: 'omit',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email,
password,
firstname,
lastname
})
})
};
and after :
import { signupAuth } from "./file";
signupAuth(email, password, firstname, lastname)
.then(response => {
})
.catch(error => {
});
// or this way
try {
const response = await signupAuth(email, password, firstname, lastname);
// do you stuff here
} catch (error) {
// handle error here
}

Related

how to use Access-Tokens for CRUD REACT JS

Given is an application for managing users. Following help files are used for this purpose:
AuthenticationAction.js
ManagementAction.js
AuthenticationAction.js is used for authentication:
export function authenticateUser(userID, password) {
console.log("Authenticate")
return dispatch => {
dispatch(getAuthenticateUserPendingAction());
login(userID, password).then(userSession => {
const action = getAuthenticationSuccessAction(userSession);
dispatch(action);
}, error => {
dispatch(getAuthenticationErrorAction(error));
}).catch(error => {
dispatch(getAuthenticationErrorAction(error));
})
}
}
function login(userID, password) {
const hash = Buffer.from(`${userID}:${password}`).toString('base64')
const requestOptions = {
method: 'POST',
headers: {
'Authorization': `Basic ${hash}`
},
};
return fetch('https://localhost:443/authenticate', requestOptions)
.then(handleResponse)
.then(userSession => {
return userSession;
});
}
function handleResponse(response) {
console.log(response)
const authorizationHeader = response.headers.get('Authorization');
return response.text().then(text => {
if (authorizationHeader) {
var token = authorizationHeader.split(" ")[1];
}
if (!response.ok) {
if (response.status === 401) {
logout();
}
const error = response.statusText;
return Promise.reject(error);
} else {
let userSession = {
/* user: data, */
accessToken: token
}
return userSession;
}
});
}
ManagementAction.js is there for the Crud Functions.
export function createUser(userID, username, password) {
console.log("Create a User")
return dispatch => {
dispatch(getShowUserManagementAction());
createaUser(userID, username, password).then(userSession => {
const action = getShowUserManagementActionSuccess(userSession);
dispatch(action);
}, error => { dispatch(getShowUserManagementErrorAction(error)); }).catch(error => { dispatch(getShowUserManagementErrorAction(error)); })
}
}
function createaUser(userID, username, password) {
const token = "whatever"
const requestOptions = {
method: 'POST',
headers: { 'Authorization': `Basic ${token}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ userID: userID, userName: username, password: password })
};
console.log(requestOptions)
return fetch('https://localhost:443/user/', requestOptions)
.then(handleResponse)
.then(userSession => {
return userSession;
});
}
question:
Now if I want to use the createaUser function instead of the hardcoded token value with the accestoken I created in login, how do I get the accesstoken and how do I have to rewrite the createaUser function ?
you can store the token you created in the local storage like this:
AuthenticationAction.js
let userSession = {
/* user: data, */
accessToken: token
}
localStorage.setItem("token", userSession.accessToken)
and you can access it as below:
ManagementAction.js
function createaUser(userID, username, password) {
const token = localStorage.getItem("token")
const requestOptions = {
method: 'POST',
headers: { 'Authorization': `Basic ${token}`, 'Content-Type': 'application/json' },
then
so you can send your token value with the request

Using Fetch API to create a Login form

So, I am making a login form and I have already implemented the fetch API
const form = {
email: document.querySelector("#signin-email"),
password: document.querySelector("#signin-password"),
submit: document.querySelector("#signin-btn-submit"),
messages:document.getElementById("form-messages")
};
let button = form.submit.addEventListener("click", (e)=> {
e.preventDefault();
const login = 'https://ffcc-app.herokuapp.com/user/login';
fetch(login, {
method: "POST",
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
},
body: JSON.stringify({
email: form.email.value,
password: form.password.value,
}),
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((err) => {
console.log(err);
});
});
I am also getting the desired output:
The problem is I have to redirect to the main page when 'login successful' else I have to display a message saying 'user does not exist'. how should I do that? What else should I add to my code?
const form = {
email: document.querySelector("#signin-email"),
password: document.querySelector("#signin-password"),
submit: document.querySelector("#signin-btn-submit"),
messages: document.getElementById("form-messages"),
};
let button = form.submit.addEventListener("click", (e) => {
e.preventDefault();
const login = "https://ffcc-app.herokuapp.com/user/login";
fetch(login, {
method: "POST",
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
},
body: JSON.stringify({
email: form.email.value,
password: form.password.value,
}),
})
.then((response) => response.json())
.then((data) => {
console.log(data);
// code here //
if (data.error) {
alert("Error Password or Username"); /*displays error message*/
} else {
window.open(
"target.html"
); /*opens the target page while Id & password matches*/
}
})
.catch((err) => {
console.log(err);
});
});
login sucess and error handled by data.error as mentioned in your screenshot
👉 https://i.stack.imgur.com/WJBh2.png
function signIn(email, password) {
var userObj = {email: email, password: password};
var jsonBody = JSON.stringify(userObj);
fetch(server + "/auth/authorization", {
// mode: "no-cors",
method: 'POST',
headers: {
"Accept-language": "RU",
"Content-Type": "application/json"
},
body: jsonBody
})
.then(response => response.json())
.then(data => {
if (data.error) {
alert("Error Password or Username");
} else {
return data;
}
})
.catch((err) => {
console.log(err);
});
}

AsyncStorage works only when app is reloaded

i set my values in Async storage while logging
fetch('http://xxxxx/xxxx/getUserDetails.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
user_id: this.state.userEmail,
})
})
.then((response) => response.json())
.then((responseJson) => {
const name = responseJson[0]['name'];
const profilePicture = responseJson[0]['profile_picture'];
const userId = responseJson[0]['id'];
const loginMode = responseJson[0]['login_mode'];
AsyncStorage.setItem('active', 'true');
AsyncStorage.setItem('userEmail', this.state.userEmail);
AsyncStorage.setItem('name', name);
AsyncStorage.setItem('profilePicture', profilePicture);
AsyncStorage.setItem('userID', userId);
AsyncStorage.setItem('loginMode', loginMode)
setTimeout(async () => {
this.setState({ isLoading: false })
this.props.navigation.navigate('userScreen');
}, 500)
})
.catch((error) => {
console.log(error);
})
}
and delete those while logging out.
fetch('https://xxxxxx/xxxx/userLogout.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: userEmail
})
}).then((response) => response.json())
.then(async (responseJson) => {
try {
const keys = await AsyncStorage.getAllKeys();
await AsyncStorage.multiRemove(keys);
this.props.navigation.toggleDrawer();
this.setState({ isLoading: false })
this.props.navigation.navigate('loginScreen');
} catch (error) {
console.log("Error clearing app data");
}
}).catch((error) => {
console.log(error);
})
but again if i login with new user the old user details is shown in login page. if i reload my app the new values stored in async storage is shown why this is happen and this is not happening?
I am using the AsyncStorage here.
async componentDidMount() {
const userEmail = await AsyncStorage.getItem('userEmail');
const name = await AsyncStorage.getItem('name');
const profilePicture = await AsyncStorage.getItem('profilePicture');
const userID = await AsyncStorage.getItem('userID');
this.getWish();
this.getAddFunction();
this.setState({ userEmail })
this.getResumeVideo(userEmail);
this.getDemoVideo();
this.getClass();
this.setState({
userEmail,
name,
profilePicture,
userID
})
this.getNotificationCount(userID);
Orientation.lockToPortrait();
this._unsubscribe = this.props.navigation.addListener('focus', () => {
this.getAddFunction();
this.getDemoVideo();
this.getResumeVideo(this.state.userEmail);
this.getClass();
this.getNotificationCount(userID);
});
}
The only place you are calling setState and tells react it should assign new value to state (and render...) it at componentDidMount, therefore React don't know it should render again.
When assigning new value to AsyncStorage you might also call setState
fetch('http://xxxxx/xxxx/getUserDetails.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
user_id: this.state.userEmail,
})
})
.then((response) => response.json())
.then((responseJson) => {
const name = responseJson[0]['name'];
const profilePicture = responseJson[0]['profile_picture'];
const userId = responseJson[0]['id'];
const loginMode = responseJson[0]['login_mode'];
AsyncStorage.setItem('active', 'true');
AsyncStorage.setItem('userEmail', this.state.userEmail);
AsyncStorage.setItem('name', name);
AsyncStorage.setItem('profilePicture', profilePicture);
AsyncStorage.setItem('userID', userId);
AsyncStorage.setItem('loginMode', loginMode)
setTimeout(async () => {
this.setState({ isLoading: false })
this.props.navigation.navigate('userScreen');
}, 500)
// here
this.setState({
name,
profilePicture,
userID
})
})
.catch((error) => {
console.log(error);
})
}

fetch api always getting fields are blank

I am trying to login using PHP in react native so I am using fetch api but when I try to login it's always saying fields are blank whereas it's not. Can somebody help me with this?
Code:
export default class App extends Component {
constructor(props) {
super(props)
this.state = {
Username: '',
Password: '',
}
}
login = () => {
const {
Username,
Password
} = this.state;
var payload = {
username: Username,
password: Password
};
this.state[payload];
var data = new FormData();
data.append("json", JSON.stringify(payload));
fetch("http://example.com/api.php", {
method: 'POST',
header: {
'Accept': 'application/json',
'Content-type': 'application/json'
},
body: data
})
.then(function(res) {
return res.json();
})
.then(function(data) {
alert(JSON.stringify(data))
})
.catch((error) => {
console.error(error);
});
}
}
Text input:
<TextInput
style={styles.input}
placeholder={'Username'}
placeholderTextColor={'#fff'}
underlineColorAndroid='transparent'
onChangeText={Username => this.setState({ Username })}
/>
<TextInput
style={styles.input}
placeholder={'Password'}
secureTextEntry={this.state.showPass}
placeholderTextColor={'#fff'}
underlineColorAndroid='transparent'
onChangeText={Password => this.setState({ Password })}
/>
If the name and password status value are not empty, try this.
let data = new FormData();
data.append("username", this.state.Username);
data.append("password", this.state.Password);
fetch("http://example.com/api.php",{
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: data
}).then((response) => response.json())
.then((res) => {
console.log(res);
}).catch(err => {
console.log(err)
})
});
OR
If you're trying to get him to JSON:
fetch("http://example.com/api.php",{
method: 'post',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: this.state.Username,
password: this.state.Password,
}),
}).then((response) => response.json())
.then((res) => {
console.log(res);
}).catch(err => {
console.log(err)
})
});
Since you are sending a request of type application/json, you should send the data directly as a JSON string:
var data = JSON.stringify(payload);

React Redux promise error - (...).then is not a function

Had a look for this in the questions that offered but this was the closest and it didnt really address my problem.
I have a code block (detailed a little way down the page) as part of a larger fetch block.. it gets to this codeblock and also runs fine if this code block is commented out i.e it carrys out a successful fetch etc and returns a JWT no problem but... add this block in and i get the following error:
TypeError: (0 , _localStorageDropDowns.confirmSelectDataExistance)(...).then is not a function
It is referring to this function in another folder (imported correctly)..
export const confirmSelectDataExistance = () => {
const companyStateShortNameJson = localStorage.getItem(COMPANYSTATESHORTNAME)
const statesJson = localStorage.getItem(STATES)
const suburbLocationsJson = localStorage.getItem(LOCATIONS)
if (companyStateShortNameJson || statesJson || suburbLocationsJson) {
console.log('something exists in localstorage')
return true
}
console.log('nothing in localstorage')
return false
}
simple function - returns true or false.
and here is the code block -its failing on the first line:
return confirmSelectDataExistance().then(isConfirmed => {
if (!isConfirmed) {
dispatch({ type: REQUEST_SELECT_DATA })
console.log('gets here!', isConfirmed)
const token = getJwt()
const headers = new Headers({
'Authorization': `Bearer ${token}`
})
const retrieveSelectData = fetch('/api/SelectData/SelectData', {
method: 'GET',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
})
.then(handleErrors)
.then(response => response.json())
.then(selectData => {
dispatch({ type: RECEIVE_SELECT_DATA, payload: selectData })
saveSelectData(selectData)
});
return saveSelectData(selectData);
}
})
From my limited experience the "confirmSelectDataExistance" is a function so why is it saying that its not?
Finally here is the whole action in its entirety so you can see how it that block is called.. as I said - comment the block out and it works perfectly..
export const requestLoginToken = (username, password) =>
(dispatch, getState) => {
dispatch({ type: REQUEST_LOGIN_TOKEN, payload: username })
const payload = {
userName: username,
password: password,
}
const task = fetch('/api/jwt', {
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
})
.then(handleErrors)
.then(response => response.json())
.then(data => {
dispatch({ type: RECEIVE_LOGIN_TOKEN, payload: data })
saveJwt(data)
return confirmSelectDataExistance().then(isConfirmed => {
if (!isConfirmed) {
dispatch({ type: REQUEST_SELECT_DATA })
console.log('gets here!', isConfirmed)
const token = getJwt()
const headers = new Headers({
'Authorization': `Bearer ${token}`
})
const retrieveSelectData = fetch('/api/SelectData/SelectData', {
method: 'GET',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
})
.then(handleErrors)
.then(response => response.json())
.then(selectData => {
dispatch({ type: RECEIVE_SELECT_DATA, payload: selectData })
saveSelectData(selectData)
});
return saveSelectData(selectData);
}
})
})
.catch(error => {
clearJwt()
console.log('ERROR - LOGIN!',error)
})
addTask(task)
return task
}
EDIT
I have finally got this to work after hacking away for hours.. Here is the finished action:
export const requestLoginToken = (username, password) =>
(dispatch, getState) => {
dispatch({ type: REQUEST_LOGIN_TOKEN, payload: username })
const payload = {
userName: username,
password: password,
}
const task = fetch('/api/jwt', {
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
})
.then(handleErrors)
.then(response => response.json())
.then(data => {
dispatch({ type: RECEIVE_LOGIN_TOKEN, payload: data })
saveJwt(data)
// Now check local storage for dropdown data..
if (!confirmSelectDataExistance()) {
dispatch({ type: REQUEST_SELECT_DATA })
const token = JSON.stringify(data)
const headers = new Headers({
'Authorization': `Bearer ${token}`
})
const retrieveSelectData = fetch('/api/SelectData/SelectData', {
method: 'GET',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
})
.then(handleErrors)
.then(response => response.json())
.then(selectData => {
dispatch({ type: RECEIVE_SELECT_DATA, payload: selectData })
saveSelectData(selectData)
});
}
})
.catch(error => {
clearJwt()
console.log('ERROR - LOGIN!', error)
})
addTask(task)
return task
}
and here is the function it calls:
export const confirmSelectDataExistance = () => {
const companyStateShortNameJson = localStorage.getItem(COMPANYSTATESHORTNAME)
const statesJson = localStorage.getItem(STATES)
const suburbLocationsJson = localStorage.getItem(LOCATIONS)
if (companyStateShortNameJson || statesJson || suburbLocationsJson) {
console.log('something exists in localstorage')
return true
}
console.log('nothing in localstorage')
return false
}
The one thing I changed from the other attempts is that I used "data" instead of calling "getJwt()". I then used the line:
const token = JSON.stringify(data)
to obtain the JWT I just got.
In the end I used #Karin s answer and ran with that. (upvoted by me)
The error is not saying that confirmSelectDataExistance is not a function, it's saying that then isn't a function on what is returned from it, which is a boolean (it would be equivalent to false.then(...), which doesn't work).
If seems like you're trying to use then as a conditional. In that case a simple if statement should work:
if (confirmSelectDataExistance()) {
// do things if it returns true
} else {
// do things if it returns false
}
export const confirmSelectDataExistance = () => {
return new Promise(function (resolve, reject) {
const companyStateShortNameJson = localStorage.getItem(COMPANYSTATESHORTNAME)
const statesJson = localStorage.getItem(STATES)
const suburbLocationsJson = localStorage.getItem(LOCATIONS)
if (companyStateShortNameJson || statesJson || suburbLocationsJson) {
console.log('something exists in localstorage')
resolve(true)
}
console.log('nothing in localstorage')
reject(false)
})
}
Try something like this:
export const confirmSelectDataExistance = new Promise((resolve, reject) => {
const companyStateShortNameJson = localStorage.getItem(COMPANYSTATESHORTNAME);
const statesJson = localStorage.getItem(STATES);
const suburbLocationsJson = localStorage.getItem(LOCATIONS);
if (companyStateShortNameJson || statesJson || suburbLocationsJson) {
console.log('something exists in localstorage');
resolve(true);
}
console.log('nothing in localstorage');
reject(false); // or resolve(false) if you want handle this situation inside then block also
});

Categories