So previously I migrated my code to use Redux in my Next.js project and I immediately ran into some issues with it.
Basically I used to fetch data from getServerSideProps()
in the previous version.
But it becomes more complex when I think about fetching from a redux action. I am using redux-thunk
.
Here is my code:
action.ts
export const FetchPosts = () => async (dispatch: Dispatch) => {
const { data } = await api.fetchPosts();
dispatch({ type: FETCH_ALL, payload: data });
}
reducer.ts
export default (state: any = [], action: AnyAction) => {
switch (action.type) {
case FETCH_ALL:
return [...state, action.payload.data]
default:
return state;
}
}
index.tsx
const Component: NextPage = () => {
const dispatch = useDispatch();
const posts = useSelector(state => state.posts);
useEffect(() => {
// Should I fetch here?
dispatch(getPosts());
}, []);
return (
<div>
{/* ... */}
</div>
);
}
export const getServerSideProps = async () => {
// Or should I fetch here?
return {
/* ... */
}
}
Can anyone help?
If the data that you are fetching important for SEO purpose you should be fetching data in getServerSideProps
. So, when the server ships the HTML to the client side, your html will be populated with the data (imagine you have an ecommerce store and you want to index your shopping item ). BUt to use the serverside redux, you should be implementing next-redux-wrapper
If the data is not important for SEO, for example, admin needs to view the user data, you can fetch the data on the client-side.