I am trying to practice redux saga,
I have a question which is not return a data from async await.
With following codes :
/src/sagas/todos/index.js
export function* fetchTodosSaga() {
console.log('Ready to fetch Todos ...');
try {
const _todos = yield call(fetchTodos);
console.log(_todos); // Not a Result Data, It is a function
yield put({
type: "FETCH_TODOS_FULFILLED",
payload: {
todos: _todos
}
});
} catch (e) {
yield put({
type: "USER_FETCH_FAILED",
message: e.message
});
}
return 'Hello';
}
/src/actions/sagas/todos.js
export const fetchTodos = (params) => async (dispatch) => {
try {
const getTodosResponse = await todosAPI.getTodos(params);
console.log(getTodosResponse.data); // It is a CORRECT data
dispatch(fetchTodosAction(getTodosResponse.data));
return Promise.resolve(getTodosResponse.data);
} catch (error) {
return Promise.reject(error);
}
}
/src/services/api/todos/index.js
export default {
async getTodos() {
try {
return await axios.get(`${ baseUrl }/${ routes.todos }`);
} catch (error) {
return Promise.reject(error);
}
}
}
And the Result of Console from chrome inspector
ƒ (_x) {
return _ref.apply(this, arguments);
}
How should i fix the issue ?
From the doc call(fn, ...args):
fn: Function- A Generator function, or normal function which either returns a Promise as result, or any other value.
But you passed a thunk to call. The thunk returns a function rather than a promise or a non-function value. That's why _todos is a function.
When you use redux-saga, you don't need to use redux-thunk. You should pass the API call function todosAPI.getTodos to the call effect creator.
E.g.
import { runSaga } from 'redux-saga';
import { call, put } from 'redux-saga/effects';
const todosAPI = {
async getTodos() {
return { data: ['a', 'b', 'c'] };
},
};
export function* fetchTodosSaga() {
try {
const _todos = yield call(todosAPI.getTodos);
console.log(_todos);
yield put({ type: 'FETCH_TODOS_FULFILLED', payload: { todos: _todos } });
} catch (e) {
yield put({ type: 'USER_FETCH_FAILED', message: e.message });
}
return 'Hello';
}
(function test() {
let dispatched = [];
runSaga({ dispatch: (action) => dispatched.push(action), getState: () => {} }, fetchTodosSaga);
})();
Output:
{ data: [ 'a', 'b', 'c' ] }