redux-saga / redux-saga

An alternative side effect model for Redux apps

Home Page:https://redux-saga.js.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Help me connect redux-saga with Nextjs 13.5 using app router

quang13 opened this issue · comments

When I tried to use saga with the Nextjs 13 router app, I got an error that I couldn't use the select statement to get redux store data. When I use useSelector to get data from the store, I can still get it normally, but in saga, I can't get it through the select function. Please help me, below is my code:

// File store.ts
import accountSagas from "../sagas/account";
import accountReducers from "./account/reducers";
import uploadSaga from "./upload/sagas";
import uploadReducer from "./upload/reducers";
import postsReducer from "./posts/reducers";
import postsSaga from "../sagas/posts";
import { logger } from "./middleware";

const rootReducer = combineReducers({
account: accountReducers,
upload: uploadReducer,
posts: postsReducer,
});

function* rootSaga() { yield all([fork(accountSagas), fork(uploadSaga), fork(postsSaga)]); }'

const sagaMiddleware = createSagaMiddleware();
const middlewares = [sagaMiddleware, logger];

const store = configureStore({
reducer: rootReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(middlewares),
});

export interface SagaStore extends Store { sagaTask?: Task; }

(store as SagaStore).sagaTask = sagaMiddleware.run(rootSaga);

const appState = (): any => store !== undefined && store.getState();
const appDispatch = (action: any | unknown): any => store.dispatch(action);

/* Types */

export type ReduxStore = typeof store;
export type ReduxState = ReturnType<typeof store.getState>;
export { store, appState, appDispatch };

// File handle of saga: post.ts
...
function* getItemBySlug(): Generator<any> {
try {
const slug = yield select(PostsReducers.dataSlugRequest);
const ress: any = yield call(axios.get, GET_BY_SLUG, {
params: { slug },
});
yield put(PostsAction.data_ItemBySlugResponse(ress.data?.item));
} catch (error: any) {
console.log("error", error?.message ?? error);
}
}

// File handle of saga: post.ts

function* getItemBySlug(): Generator<any> {
try {
const slug = yield select(PostsReducers.dataSlugRequest);
const ress: any = yield call(axios.get, GET_BY_SLUG, {
 params: { slug },
});
yield put(PostsAction.data_ItemBySlugResponse(ress.data?.item));
 } catch (error: any) {
console.log("error", error?.message ?? error);
}
}

You can try replacing this line of above code
const slug = yield select(PostsReducers.dataSlugRequest);
to
const slug = yield select(state => state.dataSlugRequest);

Hello, I have solved this problem. The reason is that I created a reducer but passed the parameters in the wrong place. Instead of the order (state, action), I passed (action, state). Therefore, I would like to close this question. Thank you