I'm writing the search result page now and I want to use dynamic route to implement. This is my search bar code,
<Link href={`/productSearchResult/${searchWord}`}>
<a className={styles.navbar_searchbar_dataResult_productItem}>
<p>{filteredData}</p>
</a>
</Link>
searchWord is the user's input, and if user click the autocompleted link, it will jump into the searchResult page.
This is my search result code,
import Navbar from "../../components/navbar"
import Head from "next/dist/shared/lib/head"
import searchResult from "../../components/searchResult"
import productList from "../../components/productList"
export default function productionSearchResult({ searchName }) {
const [searchedProducts, setSearchedProducts] = useState([])
console.log(searchName);
const productsInformation = searchResult(searchName);
productsInformation.then(function(result) {
setSearchedProducts(result.props)
})
return (
<div>
<Head>
<title>Growcery | Search Result</title>
<meta name="description" content="Your search result | Growcery" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Navbar/>
<main>
<p>Showing results for {searchName}</p>
<productList products={searchedProducts} />
</main>
</div>
)
}
export async function getServerSideProps({ product_name }) {
const productName = product_name;
const res = await fetch(`${process.env.NEXT_PUBLIC_API_LINK}search-products/${productName}/`);
let data = "";
if (res)
data = await res.json();
return {
props: {
products: data.data || "",
}
}
}
I wrote a console.log(searchName) to see if the code can fetch the searchName, here is the screenshot of my google Chrome.
route path
console.log(searchName) in google chrome
But I can only see undefined in my chrome terminal.
<Route exact path="/productSearchResult/:name?"></Route>
------------------------------------------------------------------------
import Navbar from "../../components/navbar"
import Head from "next/dist/shared/lib/head"
import searchResult from "../../components/searchResult"
import productList from "../../components/productList"
export default function productionSearchResult({props}) {
const [searchedProducts, setSearchedProducts] = useState([])
let searchName = props.match.params.name;
console.log(searchName);
const productsInformation = searchResult(searchName);
productsInformation.then(function(result) {
setSearchedProducts(result.props)
})
return (
<div>
<Head>
<title>Growcery | Search Result</title>
<meta name="description" content="Your search result | Growcery" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Navbar/>
<main>
<p>Showing results for {searchName}</p>
<productList products={searchedProducts} />
</main>
</div>
)
}
export async function getServerSideProps({ product_name }) {
const productName = product_name;
const res = await fetch(`${process.env.NEXT_PUBLIC_API_LINK}search-products/${productName}/`);
let data = "";
if (res)
data = await res.json();
return {
props: {
products: data.data || "",
}
}
}