next.js i have this url: "http://localhost:3000/forum" and if user go "http://localhost:3000/forum/{postId}" i want to send user again "http://localhost:3000/forum"
i also used this (my folder structure is App. Not pages):
import { useRouter } from 'next/navigaiton';
and there is no problem with going to page. but i dont want to send user to new page. ı want to update the params while keeping the user on the same screen.
and i did this:
// Function to handle selecting a topic
const handleSelectTopic = (topicID: string) => {
// Update the URL to include the selected topicID
// router.replace(`/forum/${topicID}`);
window.history.pushState({}, "", `/forum/${topicID}`)
// window.history.pushState(null, 'test', `/forum/${topicID}`);
// setName(`${topicID}`);
// router.push({
// pathname: '/forum',
// query: {
// pageId: topicID // update the query param
// }
// },
// undefined,
// { shallow: true },
// )
};
This is working for updateding params of url but if user have a link as that: http://localhost:3000/forum/8e90eb70-83d3-11ee-a39e-06efd237be49
and when clicked on this, Its routing to not found page how can i directly send user to "http://localhost:3000/forum" path.
I have this resources: https://github.com/vercel/next.js/discussions/48110 https://nextjs.org/docs/pages/building-your-application/routing/pages-and-layouts and i used this package: https://github.com/47ng/next-usequerystate
But i want that is there any easy way for that?
I fix this problem in next.js with app directory. With creating 2 file.
as:
- forum (folder)
- page.tsx (file)
- [slug] (folder)
- page.tsx (file)
And dont forget these 2 page.tsx file are same but i just check is there any params on url: this is forum > page.tsx file
"use client";
import { ForumLayout } from "@/components";
import StorageService from "@/utils/Storage";
import React from "react";
export default function Forum() {
// const sessionToken = StorageService.getAuthToken();
// const feed = StorageService.getDiscoverFeed();
return (
<React.Fragment>
<ForumLayout />
</React.Fragment>
);
}
and this is forum > [slug] > page.tsx file:
"use client";
import { ForumLayout } from "@/components";
import { PostDetailModel } from "@/utils/models";
import React from "react";
export default function ForumTopic({ params }: { params: { slug: string } }) {
var topicId = params.slug;
console.log("topicId", topicId);
const { post } = PostDetailModel(topicId);
console.log("post", post);
return (
<React.Fragment>
{/* Forum topics accessed from the link */}
<ForumLayout topic={post} />
</React.Fragment>
);
}
i render it if there is any selected topic or not. this page directory structure fix my problem.