So I have been trying to use next-redux-wrapper
and make request to my api endpoint to fetch blogs with redux-saga
. I'm able to fetch data to the state. My only doubt here is, what is the correct way to get a particular value from the state; I know the two solutions are using store.getState()
inside getServerSideProps()
or using useSelector()
hook in the function component?
As far as I understand, using useSelector()
would go against server-side rendering as it calls the data in the client side, i think. Is it correct?
My code using useSelector()
:
export default function BlogsList(){
const blogs = useSelector(state => state.blogReducer.blogReducer.blog);
return(
<div className="mainCon">
<ul>
{blogs.map((item) => (
<li key={item.author}>
<span>{item.author}</span><br/>
<span>{item.title}</span>
<h4>{item.body_delta}</h4>
<p>{item.body_html}</p>
<p>{item.created_on}</p>
</li>
))}
</ul>
</div>
);
}
export const getServerSideProps = wrapper.getServerSideProps( async ({store, req}) =>{
store.dispatch({type: FETCH_BLOG_LIST});
store.dispatch(END);
await store.sagaTask.toPromise();
});
My code using store.getState()
:
export default function BlogsList({blogs}){
return(
<div className="mainCon">
<ul>
{blogs.map((item) => (
<li key={item.author}>
<span>{item.author}</span><br/>
<span>{item.title}</span>
<h4>{item.body_delta}</h4>
<p>{item.body_html}</p>
<p>{item.created_on}</p>
</li>
))}
</ul>
</div>
);
}
export const getServerSideProps = wrapper.getServerSideProps( async ({store, req}) =>{
store.dispatch({type: FETCH_BLOG_LIST});
store.dispatch(END);
await store.sagaTask.toPromise();
const blog = store.getState();
const blogs = blog.blogReducer.blog;
return { props: {blogs}, };
});
Which approach properly follows server-side rendering logic?
Your code using store.getState ():
is the correct approach and as you mentioned, useSelector is used to get state on the client side. With next-redux-wrapper two stores are created, one for the server(getStaticProps, getServerSideProps) and one for the client