简体   繁体   中英

How to update path on component mount?

I have a login/signup form in one component and I'm trying to update the URL path accordingly. But I have a few issues I'm trying to address. I am using Firebase fetchSignInMethodsForEmail() to check if user exists if it's an empty array it is a new user.

  1. when prop new is true. It will render the create password input and update URL from /login to /signup. Ideal output: https://id.atlassian.com/login type any random email address. url changes from login -> signup and create password input mount.

The current output is that /signup will only trigger(display) if and only if I clicked Form.Item which is wrapped with <Link to="/signup">...</>

  1. If I directly type path /signup how can I trigger redux to dispatch an action that will update new

I tried using useRouteMatch to get path and if it equals /signup then dispatch an action to toggle new but by doing this I'm getting too many re-renders error

if(match.path === "/signup")
{
     dispatch(new());
}

Current Route:

<Switch>
  <Route path="/signup" component={Login} />
  <Route path="/login" component={Login} />
</Switch>

Login.js

  const dispatch = useDispatch();
  const { new } = useSelector(
    state => state.auth
  ); 
  const match = useRouteMatch();
  if(match.path === "/signup)
  {
     dispatch(new());
  }

  return (
    <Form>
        Email
      <Form.Item>
          <Input placeholder="Username" />
      </Form.Item>

        {new ? (
          <div>
          <Link to="/signup">
            Create password
            <Form.Item>
                <Input.Password placeholder="Password"/>
            </Form.Item>
           </Link>
          </div>
        ) : (
          <div>
            Enter your password
            <Form.Item>
                <Input.Password placeholder="Password"/>
            </Form.Item>
          </div>
      )}
      </Link>
      {new ? (
        <Button>
          Sign up
        </Button>
      ) : (
        <Button>
          Log in
        </Button>
      )}
    </Form>
  );
});

If I understand correctly, you want to dispatch this action once, after the mounting phase of your component. In that case, the useEffect() hook might be a good fit:

import { useEffect } from "react";

...

const match = useRouteMatch();

const onMount = () => {
  /* This callback is invoked after mount */
  if(match.path === "/signup)
  {
     dispatch(new());
  }
}

/* The effect hook runs the following callback as a side effect */
useEffect(() => {
  onMount();
}, []); /* Empty array causes the effect to only run once (on mount) */

For more information on why the empty array causes the effect callback to trigger once, see this answer .

Also, a small suggestion - consider renaming the new() function and new variable to something else (perhaps New ?), seeing that new is a reserved keyword.

Hope that helps!

Update

You could take the following "non-redux" approach that achieves the login/sign up flow that's similar to the link your provided:

const { useState } from "react";

const AuthForm = () => {

  /* Define state shape */
  const [state, setState] = useState({ 
    username : "", 
    password : "", 
    isNew : false 
  });

  /* Field update helpers */
  const setUsername = (username) => setState(s => ({ ...s, username }))
  const setPassword = (password) => setState(s => ({ ...s, password }))

  const login = async () => {
    const { username, password } = state;
    /* login logic */
  }

  const signup = async () => {
    const { username, password } = state;
    /* signup logic */
  }

  const checkUsername = async () => {

    /*
    const response = await fetch("/api/check-username-exists", { 
        method : "POST", 
        body : JSON.stringify({ userNameToCheck : state.username })
    })

    // say that response.found is true when user name we checked 
    // does exist in database
    setState(s => ({ ...s, isNew : !response.found }));
    */
  }

  const renderFields = () => {

    if(!username) {
      return <>
        <Form.Item>
          <Input placeholder="Username" 
                 onChange={e =>setUsername(e.target.value)} />
        </Form.Item>
        <Button onClick={checkUsername}>
          Continue
        </Button>
      </>
    }
    else {
      return <>
      <p>Login as { state.username }</p>
      {
        state.isNew ? (<div>
          <p>Create password</p>
          <Form.Item>
            <Input.Password placeholder="Password"
                onChange={e => setPassword(e.target.value)}/>
          </Form.Item>
          <Button onClick={signup}>
            Sign up
          </Button>
        </div>) : (<div>
          <p>Enter your password</p>
          <Form.Item>
            <Input.Password placeholder="Password" 
                 onChange={e => setPassword(e.target.value)}/>
          </Form.Item>
          <Button onClick={login}>
            Log in
          </Button>
        </div>)
      }
      </>
    }
  }

  return (<Form>{renderFields()}</Form>);
}

Please keep in mind that this is just skeleton code intended to illustrate a "non-redux" way of implementing the form. It will need to be completed with appropriate calls to your backend/API, etc however hopefully this gives you some ideas on how to achieve what your require :-)

Maybe use the local state to control rather than redux store?

const [isNew, setIsNew] = useState(location && location.pathname === '/signup')

function handleEmailCheck(event) {
  // use Firebase fetchSignInMethodsForEmail() to check the email
  // and use setIsNew() & history.pushState() to update address bar render content
}

return (
  <Form>
      Email
    <Form.Item>
        <Input placeholder="Username" onBlur={handleEmailCheck} />
    </Form.Item>
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM