skip to Main Content

I am taking email and password from the user and if password matches user will be redirected to account page.

Login page:

import React, { useState, useEffect } from "react";
import Axios from "axios";
import { useNavigate } from 'react-router-dom';
import Account from "./account";
const Login = () =>  {
    const navigate = useNavigate();
    const [products, setProducts] = useState([]);
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

  
    const Submit = async (e) => {
      e.preventDefault();

      const { data } = await Axios.get(
        `http://localhost:8080/api/login/${email}`
      );
      let parseData = JSON.parse(data.response);
  
      setProducts(parseData);
      console.log(password);
      console.log(products.password);


   if(products.password==password){
    window.isLoggedin=1;
    <Account props={products} />
    navigate(`/account`)

   }
   else{
    navigate(`/sign-in`)

   }

        
      
    };




    return (
      <form   >
        <h3>Sign In</h3>
        <div className="mb-3">
          <label>Email</label>
          <input
            type="email"
            name="email" 

            className="form-control"
            placeholder="Enter email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
        </div>
        <div className="mb-3">
          <label>Password</label>
          <input
            type="password"
            name="password" 

            className="form-control"
            placeholder="Enter password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
        </div>
        <div className="d-grid">
          <button type="submit" onClick={Submit} className="btn btn-primary">
           Sign In
          </button>
        </div>
        <p className="forgot-password text-right">
          Not registered <a href="/sign-up">sign up?</a>
        </p>
      </form>

    )
    


}

export default Login;

Account Page:

import React, { useState, useEffect } from "react";
import './account.css';
import { useNavigate } from 'react-router-dom';
import Login from "./login";

const Account = (props) =>  {

    const navigate = useNavigate();

    const check =()=>{
        console.log(props.email);

        if(window.isLoggedin==0)
        navigate(`/sign-in`)
    }
  useEffect(() => {
    check();
  }, []);



    return (
    
<div class="container d-flex justify-content-center">
    <div class="card p-3 py-4">
        <div class="text-center"> 
            <h3 class="mt-2">Username</h3>
            
            <div class="row mt-3 mb-3">
            
              <div class="col-md-4">
                <h5>Email</h5>
                <span class="num">10</span>
              </div>
              <div class="col-md-4">
              <h5>Location</h5>
                <span class="num">10</span>
              </div>
              <div class="col-md-4">
              <h5>{props.products}</h5>
                <span class="num">10</span>
              </div>
            
            </div>
            
            <hr class="line"></ hr>
            
              <div class="social-buttons mt-5"> 
               <button class="neo-button"><i class="fa fa-facebook fa-1x"></i> </button> 
               <button class="neo-button"><i class="fa fa-linkedin fa-1x"></i></button> 
               <button class="neo-button"><i class="fa fa-google fa-1x"></i> </button> 
               <button class="neo-button"><i class="fa fa-youtube fa-1x"></i> </button>
               <button class="neo-button"><i class="fa fa-twitter fa-1x"></i> </button>
              </div>
              
             <div class="profile mt-5">
             
             <button class="profile_button px-5" >Log Out</button>

        </div>
               
        </div>
    </div>
</div>
    );

}

export default Account;

Here i want to pass products array from Login page to Account page.
Please guide me how to send data from one page to another in react JS.
I did some solutions availabe but i am unable to pass the data.

4

Answers


  1. You can use localStorage to save your products array from Login component then getlocalStorage at Acount component.(context,useReducer,redux).

    Login or Signup to reply.
  2. You aren’t returning the Account component here:

    if(products.password==password){
        window.isLoggedin=1;
        <Account props={products} />
        navigate(`/account`)
    
       }
       else{
        navigate(`/sign-in`)
    
    }
    

    Return it like this:

    return <Account props={products} />
    
    Login or Signup to reply.
  3. This Stackoverflow post describes how to pass data from one page to another, using useNavigate and useLocation.

    Login or Signup to reply.
  4. It is a bad idea to return user passwords from the server. So try to refactor your code so that the app does not spread your user secret to the whole world. Password validation must be done on the server-side and return the validation status as part of the response. The request method should use the post method and post the user credentials as the request payload.

    And to pass data to Account component you can use navigate("/account", { state: parseData })

    Login.jsx

      ...
      
      const { data, isAuthorized } = await Axios.post(
        `http://localhost:8080/api/login`, { email, password }
      );
    
      if (isAuthorized) {
        setPassword(undefined);
        const parseData = JSON.parse(data);
        navigate("/account", { state: parseData })
      }
    
      ...
    

    Another approach is to use react-tracked, a state usage tracking library. And if you want a persisting state, you can use useReducer with localStorage

    ./store.js

    import { useState } from "react";
    import { createContainer } from "react-tracked";
    
    const initialState = {
      isLogedin: false,
      data: undefined,
    };
    
    const useAppState = () => useState(initialState);
    
    export const { Provider: SharedStateProvider, useTracked: useSharedState } =
      createContainer(useAppState);
    

    ./useAuth.js

    import { useCallback, useMemo } from "react";
    import axios from "axios";
    import { useSharedState } from "./store";
    
    export const useAuth = () => {
      const [appState, setAppState] = useSharedState();
    
      const login = useCallback(
        async ({ email, password }) => {
          const { data, isAuthorized } = await axios.post(
            `http://localhost:8080/api/login`,
            { email, password }
          );
          isAuthorized && setAppState({ isLogedin: true, data });
        },
        [setAppState]
      );
    
      const logout = useCallback(() => {
        setAppState({ isLogedin: false, data: undefined });
      }, [setAppState]);
    
      const isLogedin = useMemo(() => {
        return appState.isLogedin;
      }, [appState]);
    
      return {
        isLogedin,
        login,
        logout,
      };
    };
    

    Login.js

    import { useCallback, useEffect, useState } from "react";
    import { useNavigate } from "react-router-dom";
    import { useSharedState } from "./store";
    import { useAuth } from "./useAuth";
    
    export default function Login() {
      const [appState] = useSharedState();
      const [email, setEmail] = useState();
      const [password, setPassword] = useState();
      const navigate = useNavigate();
      const auth = useAuth();
    
      useEffect(() => {
        appState.isLogedin && navigate("/account");
      }, [appState, navigate]);
    
      const loginHandler = useCallback(() => {
        auth.login({ email, password });
      }, [auth, email, password]);
    
      return (
        <>
          <h2>Login Page</h2>
          <div>
            Email:
            <input
              type="email"
              name="email"
              onChange={(e) => setEmail(e.target.value)}
            />
          </div>
          ...
          <button onClick={() => loginHandler()}>Login</button>
        </>
      );
    }
    

    Account.js

    import React, { useCallback, useEffect } from "react";
    import { useSharedState } from "./store";
    import { useNavigate } from "react-router-dom";
    import { useAuth } from "./useAuth";
    
    export default function Account() {
      const [appState,] = useSharedState();
      const { data: user } = appState;
      const auth = useAuth();
      const navigate = useNavigate();
    
      useEffect(() => {
        !appState.isLogedin && navigate("/login");
      }, [appState, navigate]);
    
      const logout = useCallback(() => {
        auth.logout()
      }, [auth]);
    
      if (!user) return null;
    
      return (
        <>
          <h2>Account Page</h2>
          <div>{user.firstName}</div>
          <div>{user.lastName}</div>
          <button onClick={() => logout()}>Logout</button>
        </>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search