I have 2 different API responses, first I get an id for a category and the second I get a list of categories based on the id category I just got, how do I send that id into action? so that the list can be directly obtained and is there a more effective way besides the way that I have done? thanks a lot
this is action my category
export const getArticleCategory = () => {
return dispatch => {
dispatch(initDataStarted());
api.get('api/article_category/list')
.then((res) => {
dispatch({
type: appConstants.GET_ARTICLE_CATEGORY,
payload: {
articleCategory: res.data.data
}
})
res.data.data.map((byIyd) => {
return api.get(`api/article/list?category_id=${byIyd.id}`)
.then((response) => {
dispatch({
type: appConstants.GET_ARTICLE,
payload: {
article: response.data.data
}
})
})
})
})
}
}
and this is my page assuming you already get the data category and list category by ID
const Article = (props) => {
const {
getArticleCategory,
listArticleByCategory,
articleCategory
} = props;
useEffect(() => {
if (articleCategory.articleCategory.length < 1) {
}
}, [])
return (
<Layout>
<Banner />
<Container className='py-5'>
<Row>
<Col xs={12}>
{articleCategory.articleCategory.map(res => {
return (
<>
<h1 className="dots pl-3 mb-5" key={res.id}>{res.category} {res.id}</h1>
{listArticleByCategory.dataArticle.map(item => {
return (
<CardNews
key={item.id}
title={item.title}
content={item.content}
image={item.image}
category={{ ...item.category }}
url='/detail/article'
type='article'
/>
)
})}
</>
)
})}
</Col>
</Row>
</Container>
</Layout>
)
}
const mapStateToProps = (state) => ({
articleCategory: state.articleCategory
})
const mapDispatchToProps = {
fetchArticleByCategory,
getArticleCategory
}
export default connect(mapStateToProps, mapDispatchToProps)(Article);
and this is reducer category
export const reducerArticleCategory = (state = initialState, action) => {
switch (action.type) {
case appConstants.GET_ARTICLE_CATEGORY :
return {
...state,
loading:false,
articleCategory:[...action.payload.articleCategory]
};
case appConstants.INIT_DATA :
return {
...state,
loading: !state.loading
}
default:
return state
}
}
and this is reducer article by category
export const reducerArticle = (state = initialState, action) => {
switch(action.type) {
case appConstants.GET_ARTICLE :
return {
...state,
loading:false,
dataArticle:[...action.payload.article]
};
case appConstants.INIT_DATA :
return {
...state,
loading: !state.loading
}
default:
return state;
}
}
Essentially when I get the category_id I send it as a parameter into the list / category api