Skip to main content

how do we pass the user id into a route in app.js?

my teammate and I are stuck on solving a critical problem, which is how do we pass the user_id from one component to another in app.js . For example, we are able to register, login, and logout perfectly; but when we try to submit information in another component like personal form it says user_id is not defined. Also we are using JWT Tokens for authorization, and authentication.

App.js

import React, { Fragment, useState, useEffect } from "react";
import "./App.css";
import {
    BrowserRouter as Router,
    Routes,
    Route,
    Navigate,
} from "react-router-dom";

import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

// import { useNavigation } from '@react-navigation/native';
import Home from "./components/Home";
import Login from "./components/Login";
import Register from "./components/Register";
import MedicalForm from "./components/MedicalForm";
import PersonalForm from "./components/PersonalForm";
import Navbar from "./components/Navbar/index";

toast.configure();

function App() {
    // we want to make sure it set to false first
    const [isAuthenticated, setAuthenticated] = useState(false);

    //this is going to the be toggle function to set the auth
    const setAuth = (Boolean) => {
        setAuthenticated(Boolean);
    };

    // this is going to check if the user is authenticated  even if the
    // page is refreshed

    async function isAuth() {
        try {
            const response = await fetch("http://localhost:4001/auth/is-verify", {
                method: "GET",
                headers: { token: localStorage.token },
            });

            const parseRes = await response.json();

            parseRes === true ? setAuthenticated(true) : setAuthenticated(false);

            console.log(parseRes);
        } catch (err) {
            console.error(err.message);
        }
    }
    useEffect(() => {
        isAuth();
    });

    return (
        <Fragment>
            <Router>
                {/* reason why we use render instead of component props is because
                              anytime we send props to a component we don't want it to remount */}
                <Navbar />
                <div className="container">
                    <Routes>
                        {/* if(!isAuthenticated){ if this is true, pass setAuth to Login, and if it comes out true, then navigate to login page
                            <Login setAuth={setAuth} />}
                        else{
                            <Navigate to="/home" />
                            } */}
                        <Route
                            exact
                            path="/login"
                            element={
                                !isAuthenticated ? (
                                    <Login setAuth={setAuth} />
                                ) : (
                                    <Navigate to="/home" />
                                )
                            }
                        />
                        <Route
                            exact
                            path="/register"
                            element={
                                !isAuthenticated ? (
                                    <Register setAuth={setAuth} />
                                ) : (
                                    <Navigate to="/login" />
                                )
                            }
                        />

                        <Route
                            exact
                            path="/home"
                            element={
                                isAuthenticated ? (
                                    <Home setAuth={setAuth} />
                                ) : (
                                    <Navigate to="/login" />
                                )
                            }
                        />
                        <Route
                            exact
                            path="/mform"
                            element={
                                isAuthenticated ? (
                                    <MedicalForm setAuth={setAuth} />
                                ) : (
                                    <Navigate to="/login" />
                                )
                            }
                        />
                        <Route
                            exact
                            path="/pform"
                            element={
                                isAuthenticated ? (
                                    <PersonalForm setAuth={setAuth} />
                                ) : (
                                    <Navigate to="/login" />
                                )
                            }
                        />
                    </Routes>
                </div>
            </Router>
        </Fragment>
    );
}

export default App;

PersonalForm.js

import React, { Fragment, useState } from "react";
// import { Link } from "react-router-dom";
import { toast } from "react-toastify";
const Personalform = (props) => {
    const [username, setUsername] = useState("");
    const [inputs, setInputs] = useState({
        first_name: "",
        last_name: "",
        pronoun: "",
        occupation: "",
        phone_number: "",
        city: "",
        state: "",
        zip: "",
    });
    const {
        first_name,
        last_name,
        pronoun,
        occupation,
        phone_number,
        city,
        state,
        zip,
    } = inputs;
    const onChange = (e) => {
        // take in every input and target the input value of name
        //like email,username, and password
        setInputs({ ...inputs, [e.target.name]: e.target.value });
    };
    const onSubmitForm = async (e) => {
        e.preventDefault();
        try {
            const body = {
                first_name,
                last_name,
                pronoun,
                occupation,
                phone_number,
                city,
                state,
                zip,
            };
            // console.log(user_id)
            const response = await fetch(
                `http://localhost:4001/pform/${props.user_id}`,
                {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        token: localStorage.token,
                    },
                    body: JSON.stringify(body),
                }
            );
            const parseRes = await response.json();
            setUsername(parseRes.username);
            if (parseRes.token) {
                // we want to save the token to our local storage
                localStorage.setItem("token", parseRes.token);
                console.log(parseRes);
                //now we want to setAuth to true
                props.setAuth(true);
                toast.success("submit succesfully"); // then use toastify
            } else {
                // if false
                props.setAuth(false); // set auth to false
                toast.error(parseRes); // set the toast to send and error
            }
        } catch (err) {
            console.error(err.message);
        }
    };
    const logout = (e) => {
        e.preventDefault();
        localStorage.removeItem("token");
        props.setAuth(false);
        toast.success("Logged out successfully");
    };
    return (
        <Fragment>
            {username}
            <h1 className="text-center my-5">Personal Form</h1>
            <form onSubmit={onSubmitForm}>
                <input
                    type="text"
                    // this is a name of an input
                    name="first_name"
                    placeholder="first_name"
                    className="form-control my-3"
                    value={first_name}
                    onChange={(e) => onChange(e)}
                />
                <input
                    type="text"
                    name="last_name"
                    placeholder="Last Name"
                    className="form-control my-3"
                    value={last_name}
                    onChange={(e) => onChange(e)}
                />
                <input
                    type="text"
                    name="pronoun"
                    placeholder="pronoun"
                    className="form-control my-3"
                    value={pronoun}
                    onChange={(e) => onChange(e)}
                />
                <input
                    type="text"
                    name="occupation"
                    placeholder="occupation"
                    className="form-control my-3"
                    value={occupation}
                    onChange={(e) => onChange(e)}
                />
                <input
                    type="text"
                    name="phone_number"
                    placeholder="phone number"
                    className="form-control my-3"
                    value={phone_number}
                    onChange={(e) => onChange(e)}
                />
                <input
                    type="text"
                    name="city"
                    placeholder="city"
                    className="form-control my-3"
                    value={city}
                    onChange={(e) => onChange(e)}
                />
                <input
                    type="text"
                    name="state"
                    placeholder="state"
                    className="form-control my-3"
                    value={state}
                    onChange={(e) => onChange(e)}
                />
                <input
                    type="text"
                    name="zip"
                    placeholder="zip"
                    className="form-control my-3"
                    value={zip}
                    onChange={(e) => onChange(e)}
                />
                <button className="btn btn-success btn-block">Submit</button>
            </form>
            <button className="btn btn-primary" onClick={(e) => logout(e)}>
                logout
            </button>
        </Fragment>
    );
};
export default Personalform;

index.js or the navbar component

import React from "react";
import {
    Nav,
    NavLink,
    Bars,
    NavMenu,
    NavBtn,
    NavBtnLink,
} from "./NavbarElements";

const Navbar = () => {
    return (
        <>
            <Nav>
                <NavLink to="/">
                    <h1>Logo</h1>
                </NavLink>
                <Bars />
                <NavMenu>
                    <NavLink to="/pform" activeStyle>
                        Personal Form
                    </NavLink>
                </NavMenu>
                <NavBtn>
                    <NavBtnLink to="/login">Login</NavBtnLink>
                </NavBtn>
            </Nav>
        </>
    );
};

export default Navbar;

Via Active questions tagged javascript - Stack Overflow https://ift.tt/eo36xOY

Comments

Popular posts from this blog

ValueError: X has 10 features, but LinearRegression is expecting 1 features as input

So, I am trying to predict the model but its throwing error like it has 10 features but it expacts only 1. So I am confused can anyone help me with it? more importantly its not working for me when my friend runs it. It works perfectly fine dose anyone know the reason about it? cv = KFold(n_splits = 10) all_loss = [] for i in range(9): # 1st for loop over polynomial orders poly_order = i X_train = make_polynomial(x, poly_order) loss_at_order = [] # initiate a set to collect loss for CV for train_index, test_index in cv.split(X_train): print('TRAIN:', train_index, 'TEST:', test_index) X_train_cv, X_test_cv = X_train[train_index], X_test[test_index] t_train_cv, t_test_cv = t[train_index], t[test_index] reg.fit(X_train_cv, t_train_cv) loss_at_order.append(np.mean((t_test_cv - reg.predict(X_test_cv))**2)) # collect loss at fold all_loss.append(np.mean(loss_at_order)) # collect loss at order plt.plot(np.log(al...

Sorting large arrays of big numeric stings

I was solving bigSorting() problem from hackerrank: Consider an array of numeric strings where each string is a positive number with anywhere from to digits. Sort the array's elements in non-decreasing, or ascending order of their integer values and return the sorted array. I know it works as follows: def bigSorting(unsorted): return sorted(unsorted, key=int) But I didnt guess this approach earlier. Initially I tried below: def bigSorting(unsorted): int_unsorted = [int(i) for i in unsorted] int_sorted = sorted(int_unsorted) return [str(i) for i in int_sorted] However, for some of the test cases, it was showing time limit exceeded. Why is it so? PS: I dont know exactly what those test cases were as hacker rank does not reveal all test cases. source https://stackoverflow.com/questions/73007397/sorting-large-arrays-of-big-numeric-stings

How to load Javascript with imported modules?

I am trying to import modules from tensorflowjs, and below is my code. test.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title </head> <body> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script> <script type="module" src="./test.js"></script> </body> </html> test.js import * as tf from "./node_modules/@tensorflow/tfjs"; import {loadGraphModel} from "./node_modules/@tensorflow/tfjs-converter"; const MODEL_URL = './model.json'; const model = await loadGraphModel(MODEL_URL); const cat = document.getElementById('cat'); model.execute(tf.browser.fromPixels(cat)); Besides, I run the server using python -m http.server in my command prompt(Windows 10), and this is the error prompt in the console log of my browser: Failed to loa...