英文:
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.
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(() => {
    if (location.state.toastMsg) {
      toast(location.state.toastMsg);
    }
  }, [location.state.toastMsg]);
  return (
    <div>
      <p>Welcome to your Dashboard</p>
      <ToastContainer />
    </div>
  );
};
export default Dashboard;
以上是您提供的代码的翻译部分。
英文:
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.
答案1
得分: 0
你在使用navigate时需要在state键中传递数据:
在你的示例中使用以下方式:
nav('/dashboard', {
  state: {
    toastMsg: toastMsg,
  },
});
然后使用const location = useLocation()来获取它。传递的对象将在location.state中。
在这里查看示例:https://codesandbox.io/s/restless-frost-ji3ww6
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。



评论