So previously I migrated my code to use Redux in my Next.js project. Althought it made it easier to scale, I do still have some issues with it.
Basically I used to fetch data from the getServerSideProps server in the previous version.
But it becomes more complex when I think about fetching from a redux action.
BTW, I am using redux-thunk.
Here is my code:
action.js
export const FetchPosts = () => async (dispatch: Dispatch) => {
const { data } = await api.fetchPosts();
dispatch({ type: FETCH_ALL, payload: data });
}
reducer.js
export default (state: any = [], action: AnyAction) => {
switch (action.type) {
case FETCH_ALL:
return [...state, action.payload.data]
default:
return state;
}
}
component.tsx
const Component:FC = () => {
const dispatch = useDispatch();
const posts = useSelector(state => state.posts);
useEffect(() => {
// Should i fetch in here?
dispatch(getPosts());
}, []);
return (
<div>
{/* ... */}
</div>
);
}
export async function getServerSideProps() {
// Should i even fetch here?
return {
props: { posts }
}
}
Can anyone help?