React Admin dynamic url based on filters in return

123 views Asked by At

I am quite beginners in coding. I have one question, hope you could help me ! I have a little function which returns a url and I try to make it dynamic, based on filters. I need to make my return dynamic, it means if one oof my filter is unset(so undefined), ex: q=undefined or size=undefined, so in my url I want to delete this part completely : "q":"${q}". my problem is this part of my url : `..."q":"${q}", "size":"${size}", "color":"${color}"}

 rowClick={(id, resource, record) => {
        setSelectedRecord(record.product)
        const { q, size, color } = filterValues
        return `?filter={"details":"${record.details}","type":"product", "q":"${q}",  "size":"${size}", "color":"${color}"}`
      }}

I want my url in return was dynamic :/ no idea how to make it :(

2

There are 2 answers

2
Fried noodles On BEST ANSWER

Well you could use some ternary operators and do as:

`?filter={${record.details ? `"details":${record.details}",`}"type":"product",${q ? `"q":${q}",`} ${size ? `"size":${size}",`}${color ? `"color":${color}",`}`

I am not sure you need all those double quotes, since it's all a string anyway so you should try not using them.

1
Ilo_Iloo On

finally, to got all my filters I used a useSearchParams from react which gives me all filters in my url directly. exemple: const [URLSearchParams] = useSearchParams()

It works perfectly for me!