Home > Enterprise >  Set state based on url params react-router v6
Set state based on url params react-router v6

Time:06-30

okay so I have this form where the user can query a search with type "radio buttons" search input and a react-select filled with categories, the button works as a link front end form for clarification

{selectedOption ?
<Link to={`/annonser${typeToRoute}${selectedOptionToRoute}${searchToRoute}`} >
                    <button>Hitta annons / mönster</button>
                    </Link>: <Link to={`/annonser${typeToRoute}${searchToRoute}`} >
                    <button>Hitta annons / mönster</button>

where I then want to query db to get data based on the url params with useParams hook and then set the state

const { type, category, search} = useParams();
    const categoryRef = db.collection("articles").where("subCategory", "==", category)

I want the user to be able to search any of the alternatives seperatly aswell I will not use any form validation to make sure the user have everything not null. Is this the right way to go about it? Because you cant have optional params in route component in v6 for some reason? Is there any other way to achieve what im trying to do or am I on the right track? Thanks in advance never done anything like this before. Let me know if my question is asked poorly since I dont have alot of experience asking questions here.

CodePudding user response:

If you want optional route path parameters then see this answer, the gist being you declare a route for each that can match. The issue here though is that the order matters, "type" would need to be provided for "category" to be optional, and both "type" and "category" would need to be provided for "search" to be optional.

Here's an example showing why this isn't ideal:

<Route path="/annonser/:type" element={.....} />
<Route path="/annonser/:type/:category" element={.....} />
<Route path="/annonser/:type/:category/:search" element={.....} />

This is ok until you want the combination of "type" and "search". If you try path="/annonser/:type/:search" then this has the same specificity as path="/annonser/:type/:category", so whichever route is listed first is the one that'll be matched.

Using the queryString method then all or none, and anything between, can be provided/optional and valid.

Example:

  • Route <Route path="/annonser" element={.....} />
  • URL "annonser?type=customType&category=foo&search=bar"

Use the useSearchParams hook to access queryString parameters.

const [searchParams] = useSearchParams();

...

const type = searchParams.get("type");         // "customType"
const category = searchParams.get("category"); // "foo"
const search = searchParams.get("search");     // "bar"

const categoryRef = db.collection("articles").where("subCategory", "==", category)

Any queryString parameter not provided, when queried, will return null.

  • Related