Next.js Discord

Discord Forum

Workaround use of parameters in server side fetching

Answered
New Guinea Freshwater Crocodile posted this in #help-forum
Open in Discord
New Guinea Freshwater CrocodileOP
I have this code:

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import Card from '@/components/Card';
import ReactPaginate from 'react-paginate';
import { filterSystem } from '@/components/FilterSystem';
import Skeleton from 'react-loading-skeleton';
import 'react-loading-skeleton/dist/skeleton.css'
import ProductsContainer from '@/components/ProductContainer';

async function getProducts(page:any) {
  const res = await fetch(`http://localhost:3000/api/products?page=${page}`);
  if (!res.ok) {
    throw new Error('Failed to fetch data');
  }
  return res.json();
}

export default function ProductsPage() {
  const [page, setPage] = useState(1);
  const [products, setProducts] = useState([]);
  return (
    <div>
      <ProductsContainer page={page} products={getProducts} />
    </div>
  );
}


but i want to get the parameters from the url, but i want to keep fetching from server side.
Answered by B33fb0n3
you can use the searchparams for serverside components. Get the searchparams and fetch depending on your searchparams. You can get the searchparams serverside via the props: https://nextjs.org/docs/app/api-reference/file-conventions/page#searchparams-optional
View full answer

1 Reply