Search code examples
javascriptreactjsreact-routerreact-router-domfetch-api

Redirection & Pass data fetched from API to another component in React JS simultaneously


I wanted to redirect from login page to dashboard upon getting a successful response from API & pass the success message fetched through API from one component to another component at the same time. By doing so, I ultimately aim to redirect user from login page to dashboard with displaying toast message received on the success response of login API.

I used the useNavigate,useLocation hooks to implement this. My code does the redirection but not able to catch the data, in "Dashboard" component, which is passed from the "Login" component. I am completely a newbie to React JS. Any help is much appreciated.

Login Component

import { useNavigate } from "react-router-dom";
import { ToastContainer, toast } from 'react-toastify';

export default function Login() {
const nav = useNavigate();

 const authenticateUser = () => {

        const endpoint = `${baseUrl}/login`;
        fetch(endpoint,
            {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(loginState)
            }).then(response => response.json())
            .then(data => {
                
                if (data.statusCode === 200) {
                    let toastMsg = data.message;
                    nav("/dashboard",{toastMsg: toastMsg});
                }
             }).catch(error => console.log(error))
    }
}

Dashboard Component

import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { useEffect } from "react";
import {useLocation} from 'react-router-dom';


const Dashboard = () => {
    const location = useLocation();
  
    useEffect(() => {
        console.log(location) 
        if (location.state.toastMsg) {

            toast(location.state.toastMsg)
        }, [location.state.toastMsg]
    }
    )
  });
    return (
      <div>
        <p>Welcome to your Dashboard</p>
        <ToastContainer />
      </div>
    );
  };
  export default Dashboard;

Below shown is the screenshot of the console tab.

Console log screenshot


Solution

  • You have to pass data in state key when using navigate: In your example use this:

    nav('/dashboard', {
      state: {
        toastMsg: toastMsg,
      },
    });
    

    Then get it using const location = useLocation() . passed object will be in location.state

    See example here: https://codesandbox.io/s/restless-frost-ji3ww6