1

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

M G
  • 13
  • 4
  • Use location.state.toasMsg to display message passed from login – Abdulah Proho Jun 08 '23 at 11:40
  • @AbdulahProho now am able to get the `toastMsg` value in `Dashboard` component as well, but the the toast message won't show when redirected from login page to dashboard page. Instead, it is showing as 2 toast messages that also only when refreshing the "Dashboard" page. Why it is so? – M G Jun 08 '23 at 11:48
  • Add useEffect where you will check if there is location.state?.toasMsg in state and show it, also add [location.state?.toastMsg] as dependency – Abdulah Proho Jun 08 '23 at 11:56
  • @AbdulahProho useEffect has to be added in "Dashboard" component or "Login" component?can u provide its sample code? – M G Jun 08 '23 at 12:00
  • Add it do dashboard component – Abdulah Proho Jun 08 '23 at 12:07
  • useEffect(() => if(location.state?.toasMsg) toast(location.state.toasMsg) ;}, [location.state?.toasMsg]) – Abdulah Proho Jun 08 '23 at 12:09

1 Answers1

0

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

Malkhazi Dartsmelidze
  • 4,783
  • 4
  • 16
  • 40
  • y. that works. now am able to get the `toastMsg` value in `Dashboard` component as well, but the the toast message won't show when redirected from login page to dashboard page. Instead, it is showing as 2 toast messages that also only when refreshing the "Dashboard" page. – M G Jun 08 '23 at 12:22
  • I have used `Useffect` to fix it.But it too has error – M G Jun 08 '23 at 12:48
  • What error does it have? – Malkhazi Dartsmelidze Jun 08 '23 at 13:26
  • parsing error: unexpected token – M G Jun 08 '23 at 13:37
  • `parsing error: unexpected token` in the `UseEffect` code . See the edited code in the original question. I have updated it with the `UseEffect` code I have used. – M G Jun 08 '23 at 13:52
  • You have syntax error. try placing this: ``` useEffect(() => { if (location.state.toastMsg) { toast(location.state.toastMsg); } }, [location.state.toastMsg]); ``` – Malkhazi Dartsmelidze Jun 08 '23 at 14:44
  • that fixed the error. but it is still showing 2 toast messages in the dashboard page.What's the solution to it? – M G Jun 08 '23 at 15:44
  • Show us ToastContainer component – Malkhazi Dartsmelidze Jun 08 '23 at 15:49
  • Actually I could see 2 same objects when did `console.log(location)` .Why 2 times data is passed to the `location` object? What's the solution to it? – M G Jun 08 '23 at 15:52
  • `ToastContainer` component is not defined anywhere else by me. it is asked to include by `react-toastify` library documentation. see https://www.npmjs.com/package/react-toastify?activeTab=readme .Actually, Getting 2 objects from login component is causing the 2 toast messages. Why 2 times data is passed to the `location` object in Dashboard component?That's unknown to me – M G Jun 08 '23 at 15:54
  • I have added the console tab screenshot to the bottom of original question for your reference. Please have a look on it. – M G Jun 08 '23 at 16:08
  • @MG If you are rendering the app into a `React.StrictMode` component and using React 18 then the components are double-mounted as a safety check. This means the `useEffect` hook used to initiate the toast is called twice, e.g. two side-effects. This is intentional in non-production builds. In production builds the component will only mount once, one side-effect. – Drew Reese Jun 08 '23 at 16:18
  • @MG You are also console logging as an unintentional side-effect in the function body, so the number of logs seen doesn't correlate to the React component lifecycle with regards to rendering to the DOM. Move the logs into a `useEffect` hook so you've 1 log per render. – Drew Reese Jun 08 '23 at 16:27