I want to get path parameters from URL but when I use useParams()
it doesn't work in Redux-Toolkit.
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 need a way to get path parameter from URLs in a way that is suitable for use in the Redux-Toolkit.
You should avoid using React Router's useParams
within your redux actions or reducers because actions and reducers are expected to be pure functions. In your case, you can pass your route parameter as a payload when dispatching your action.
export const getArticleTitle = createAsyncThunk<ArticleData[], void, {
rejectValue: AxiosError }>("article/fetchAllArticle",
async (title, { rejectWithValue }) => {
try {
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;
}
});
And you can dispatch in your component like this;
const MyComponent = () => {
const { title } = useParams();
useEffect(() => {
dispatch(getArticleTitle(title))
}, [dispatch, title])
}
Hope this helps;