Bagaimana saya bisa memanggil komponen nominate.js jika token valid dari komponen CreateLink yang ada ?

CreateLink.js

    const CreateLink = () => {
    const [isFormCreated, setIsFormCreated] = useState(false);
    const onClickEnableForm = () => setIsFormCreated(true);
    const [email, setEmail] = useState("");
    const [token, setToken] = useState("");
    const [tokenUrl, setTokenUrl] = useState("");
    const { handleSubmit, register, formState: { errors } } = useForm();

    const onSubmit = () => {
        const fetchData = async () => {
            try {
                localStorage.setItem("userEmail", email);
                const res = await Axios.post('http://localhost:8000/service/createlink', { email, token});
                if (res.data) {
                    console.log("Link token created:" + res.data);
                }
            } catch (e) {
                console.log(e);
            }
        }
        fetchData(); 
    }

    const validateLink = () =>{
        const fetchData = async () => {
            try {
                const email = localStorage.getItem("userEmail");
                const res = await Axios.post('http://localhost:8000/service/validatelink', { params: { email} });
                if (res.data) {
                    const validToken = res.data[0].token;
                    // if the token is valid, how can call the `nominate.js` component from  here 
                    // by attaching the token to the url ?
                }
            } catch (e) {
                console.log(e);
            }
        }
        fetchData(); 
    }

    return (
       
        <div className="App">
            <h1>Create Link</h1>
            <form onSubmit={handleSubmit(onSubmit)} className="linkForm inputForm">
                <div className="inputField" >
                    <input name="email" 
                    placeholder="email" 
                    type="text" 
                    value={email}
                    {...register('email',{
                        required: "Email is required",
                        pattern: {
                          value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
                          message: "Invalid email address"
                        }
                      })}
                    onChange={(e) => setEmail(e.target.value)}
                    />
                    <span className="loginErrorTextFormat">{errors.email && <p>{errors.email.message}</p>}</span> 
                </div>
                <div className="inputField" >
                    <input placeholder="token" 
                    name="token" 
                    type="text" 
                    value={token}
                    {...register('token',{
                        required: "Token is required"
                      })}
                    onChange={(e) => setToken(e.target.value)}
                    />
                    <span className="loginErrorTextFormat">{errors.token && <p>Input is not valid</p>}</span> 
                </div>
                <span className="getlinkbutton">
                    <input type="submit"/>
                </span><br></br>
                <span className="getlinkbutton">
                    <button type="button" onClick={validateLink}>Get Link</button>
                </span>
                {
                    <div className="linkdetails nominationlink">
                        {tokenUrl}
                    </div>
                }
            </form>
            
        </div>

    )
}

export default CreateLink

nominate.js

const formFields = [
    ["Name of Nominee", "nominate someone"],
    ["email", "nominee email"],
    ["description", "reason for nomination"],
    ["nominatedby", "nominated by"]
];
const Nominate = () => {
    return (
        <div>
            <h1>Nominate</h1>
            <form className="linkForm inputForm">
                    {formFields.map(([name, value]) => {
                        return (
                        <div className="inputField" key={name}>
                            { 
                            name === "description" ? (
                                <textarea  placeholder={value} name={name} />
                            ) : (
                                <input placeholder={value} name={name} type="text" />
                            ) }
                        </div>
                        );
                    })}
                    <span className="nominatebutton">
                    <input type="submit" />
                    </span>
                    
                </form>
        </div>
    )
}

export default Nominate

Aplikasi.js

import './App.css';
import "./cssmodules/dashboard.css";
import "./cssmodules/createLink.css";
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import Dashboard from "./components/dashboard";
import CreateLink from "./components/createLink";
import Nominate from "./components/nominate";

function App() {
  return (
    <Router>
        <div>
          <div className="navbar-nav">
            <a><Link to={'/'} className="nav-link"> <b>Dashboard</b> </Link></a>
            <a><Link to={'/createLink'} className="nav-link"> <b>Create Link</b> </Link></a>
          </div>
          <Switch>
              <Route exact path='/' component={Dashboard} />
              <Route exact path='/createLink' component={CreateLink} />
              <Route exact path='/nominate' component={Nominate} />
          </Switch>
        </div>
      </Router>
  );
}

export default App;
1
soccerway 12 Mei 2021, 08:54

1 menjawab

Jawaban Terbaik

Jika Anda ingin mengirim parameter rute tambahan ke komponen Nominate maka saya menyarankan perubahan berikut:

  1. Edit jalur path='/nominate' untuk menerima parameter token.

    <Route path='/nominate/:token' component={Nominate} />
    
  2. Perbarui Nominate untuk menggunakan parameter rute dari objek match.

    import { useParams } from 'react-router-dom';
    
    const Nominate = () => {
      const { token } = useParams();
    
      return (
        <div>
          <h1>Nominate</h1>
          <form className="linkForm inputForm">
            ...
          </form>
        </div>
      )
    }
    
  3. Gunakan objek history untuk mengeluarkan navigasi imperatif di komponen CreateLink.

    import { useHistory } from 'react-router-dom';
    
    const CreateLink = () => {
      const history = useHistory();
    
      ...
    
      const validateLink = () =>{
        const fetchData = async () => {
          try {
            const email = localStorage.getItem("userEmail");
            const res = await Axios.post(
              'http://localhost:8000/service/validatelink',
              { params: { email} },
            );
            if (res.data) {
              const validToken = res.data[0].token;
              if (/* token is valid */) {
                history.push(`/nominate/${validToken}`); // <-- navigate
              }
            }
          } catch (e) {
            console.log(e);
          }
        }
        fetchData(); 
      }
    
1
Drew Reese 12 Mei 2021, 06:25