Search code examples
reactjsnext.jsserver-sidenext.js13

How to get one or multiple params/query and call api request in server components using next js v13.4


import { getAllProductsRequest } from "../../APIRequest/products/productsApi";
import Product from "../../components/common/product/product";
import DrawerComponents from "./_components/drawer";
import Filter from "@components/common/filter/filter";

const Store = async ({ searchParams }) => {
  let searchKeyword = searchParams.search || "0";
  const min = searchParams.min;
  const max = searchParams.max;
  const brand = searchParams.brand;
  const category = searchParams.category;

  let data = await getAllProductsRequest(1, 100, `${searchKeyword}&min=${min}&max=${max}&brand=${brand}&category=${category}`);

  if (data?.total?.length < 1) {
    return (
      <div className="container">
        <h1 className="text-2xk">No products available</h1>
      </div>
    );
  }
  return (
    <div className="px-3 py-8 mx-auto ">
      
    </div>
  );
};

export default Store;

I got this result:http://localhost:4000/list-product-global/1/100/sam&min=undefined&max=undefined&brandsymphony

I want to get when something params get undefined to remove undefined params and get the url like this: http://localhost:4000/list-product-global/1/100/sam&brand=symphony


Solution

  • Straight forward solution

    You can simply create an object of data, filter them and finally stringify them using URLSearchParams cunstructor.

    const createParams = (obj) => {
        return new URLSearchParams(Object.fromEntries(Object.entries(obj).filter(([,value]) => value !== undefined))).toString()
    }
    
    console.log(createParams({name: "John", un: undefined, another: 1}))
    // name=John&another=1
    

    Safer solution

    you can use qs library which safely stringifies and parses the value.

    console.log(qs.stringify({name: "John", un: undefined, another: 1}));
    // name=John&another=1
    
    console.log(qs.stringify({ a: null, b: undefined }));
    // a=
    

    Worth to know

    the tool you are using to make the requests might support params stringify internally. you may want to check that.