skip to Main Content

I want to get parameters from URL but when I use useParams() it doesn’t work in redux toolkit, please help to solve it?

here is an example of the code:

export const getArticleTitle = createAsyncThunk<ArticleData[], void, { rejectValue: AxiosError }>("article/fetchAllArticle", async (_, { rejectWithValue }) => {
  try {
    let { title } = useParams();
    const newsid = title!.split("-").join(" ");
    const response = await artikelService.getArtikelIni(newsid);
    return response as ArticleData[];
  } catch (error) {
    if (error instanceof AxiosError) {
      return rejectWithValue(error);
    }
    throw error;
  }
});

I’m hoping to find a way to get parameter from URLs in a way that is suitable for use in the Redux toolkit.

2

Answers


  1. I am assuming, you have url like this:

    https://example.com/news/ABC-123-ABC

    const title = location.pathname.slice(location.pathname.lastIndexOf('/')+1); //ABC-123-ABC
    

    It will return the text after the last index of / like useParams

    Use URLSearchParams API to get Query parameters like ?title=abc

    const parameter = new URLSearchParams(window.location.search);
    const title = parameter.get('title'); // parameter name 
    
    Login or Signup to reply.
  2. Use JS native search params instaed of react hook

    const urlParams = new URLSearchParams(queryString);
    const product = urlParams.get('product')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search