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

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

How to split a rinex file if I need 24 hours data

Trying to divide rinex file using the command gfzrnx but getting this error. While doing that getting this error msg 'gfzrnx' is not recognized as an internal or external command Trying to split rinex file using the command gfzrnx. also install'gfzrnx'. my doubt is I need to run this program in 'gfzrnx' or in 'cmdprompt'. I am expecting a rinex file with 24 hrs or 1 day data.I Have 48 hrs data in RINEX format. Please help me to solve this issue. source https://stackoverflow.com/questions/75385367/how-to-split-a-rinex-file-if-i-need-24-hours-data