how to stay in new data when refresh the page
in App.js
<Link to={"/Team"} state={{ teamId: team.id,teamName:team.name }}>{team.name}</Link>
in Team router page
const [sTater,setSTater] = useLocation().state;
<Menu className={`menu2`} onClick={onClickMenu2}>
{teamList.map((n, idx) => { return <Menu.Item key={n.id}>{n.name}</Menu.Item> })}
</Menu>
const onClickMenu2 = ({ key }) => {
let curname = teamList.filter(n=>n.id===key)[0];
setSTater({'teamId':key,'teamName':curname.name});
}
I use sTater to show the id and name in page. For example team05. teamList in codes is from an axios request.
When I change a team it works well. For example team14 data. But now I refresh the page. It turns back to the old data team05. It seems that setSTater doesn't work. Why? And how can I stay with team14 data when refresh the page. P.S. I don't what to use /Team:id in address. I just want to hide the id
const [sTater, setSTater] = useLocation().state;
appears to be incorrect. The passed route state
is an object, not an array with "state" and `"setState".
Assuming that in your code you are correctly accessing the route state and saving it to local state, you'll need to also persist the component state to something like localStorage so it persists through page reloads. Remember that the page and React app exist only in memory. When the page is reloaded, the existing page is thrown away and the React app is mounted new with initial state.
The flow will likely look like the following:
const { state } = useLocation();
const [sTater, setSTater] = useState(() => {
// if passed route state, initialize from route state
if (state?.teamId && state?.teamName) {
return state;
}
// else initialize from any persisted data or default fallback
return JSON.parse(localStorage.getItem("sTater")) || { teamId: "", teamName: "" };
});
// Persist sTater state to localStorage
useEffect(() => {
localStorage.setItem("sTater", JSON.stringify(sTater));
}, [sTater]);