Home > Back-end >  How can i send data to my parent component?
How can i send data to my parent component?

Time:08-18

Im doing a user uath with google API in reactjs. I have my login component that if the loggin is successfull it redirects to another component called Dashboard.

App.js:

import './App.css';
import Login from './atoms/Login';
import { BrowserRouter , Routes, Route } from 'react-router-dom';
import Dashboard from './pages/Dashboard';

function App() {
  return (
    <BrowserRouter>
    <Routes>
      <Route path="/dashboard" element={<Dashboard/>} />
      <Route exact path="/" element={<Login/>} />    
    </Routes>
    </BrowserRouter>
  );
}

export default App;

This is my Login.js:

import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom';
import jwt_decode from 'jwt-decode';

const Login = () => {

  const navigate = useNavigate()
  const [user, setUser] = useState({})

  function handleCallbackResponse(response){
    var userData = jwt_decode(response.credential); //Token with the login user Data
    setUser(userData); //Store user Data 
    /* console.log(userData) */
    document.getElementById('signInDiv').hidden = true;
    navigate('/dashboard');
  }

  function handleSignOut(event) {
    setUser({}) //Empy the user Data
    document.getElementById('signInDiv').hidden = false;
  }

    useEffect(()=>{
        /*global google*/
        google.accounts.id.initialize({
          client_id:"186813496344-0j9cjp3klq5igcsk8a2vcdm5gcosner8.apps.googleusercontent.com",
          callback: handleCallbackResponse
        })
    
        google.accounts.id.prompt();
    
    
        google.accounts.id.renderButton(
          document.getElementById('signInDiv'),
          {theme: 'outline', size: 'medium'}
        )
    
      }, []);

  return (
    <div>
        <div id="signInDiv"></div>
      {
        //If user objetc is not empty show sign out button
        Object.keys(user).length !== 0 &&
      <button onClick={(e)=>handleSignOut(e)}>Sign Out</button>
      }
      {user && 
        <div>
          <img src={user.picture} alt="" />
          <h3>{user.name}</h3>
        </div>
      }
    </div>
  )
}

export default Login

Im storing my user data in an object using a useState hook.

This is my Dashboard component:

import React from 'react'
import Navbar from '../organisms/Navbar'
import './Dashboard.css'

const Dashboard = () => {
  return (
    <div className='dashboard'>
        <h2>Mateo Ghidini</h2>
        <Navbar/>
        <div className='content'>
            <h1>Welcome to my Dashboard</h1>
        </div>
    </div>
  )
}

export default Dashboard

As you can see in the h2 tag i hardcoded the username. How can i to send the stored user data in my login component to my dashboard component, so that i can show dinamically?

CodePudding user response:

A very easy to understand solution would be to simply "lift the state" i.e. move user state to App.js and then pass the values down to the components that need it:

function App() {
  const [user, setUser] = useState({})
  return (
    <BrowserRouter>
    <Routes>
      <Route path="/dashboard" element={<Dashboard user={user} />} />
      <Route
        exact
        path="/"
        element={<Login user={user} setUser={setUser} />}
      />    
    </Routes>
    </BrowserRouter>
  );
}

However, a better approach would be to do it using React Context or similar approach. This article explains how to use React Context for sharing authentication state through the app: https://www.digitalocean.com/community/tutorials/react-manage-user-login-react-context

CodePudding user response:

The best solution is to use react-redux or something similar. In your case, it is more useful because the user info could be needed in another component which nested more deeply.

function handleSignOut(event) {
  ... ... ...
  // setUser({}) //Empy the user Data
  dispatch(setUserInfo({}));
  ... ... ...
}

function handleCallbackResponse(response){
  var userData = jwt_decode(response.credential); //Token with the login user Data
  // setUser(userData); //Store user Data 
  dispatch(setUserInfo(userData))
  ... ... ...
}

in another component...

const userData = useSelector(state => state.userInfo)

For more detail, please have a look at this link.

https://react-redux.js.org/

  • Related