Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

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

  1. Are the async and await in the right places given this arrow function.
  2. What about the const at the start? Is that okay?
  3. 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)
  4. 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 };
question from:https://stackoverflow.com/questions/65903266/is-this-a-sound-implementation-of-a-signup-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...