问题
I'm using redux-saga
to fetch server api data.
My question is that I'm trying to design following code.
However yield put(get01Action(members));
which is commented out has following Syntax error.
A 'yield' expression is only allowed in a generator body.
I don't know how to manage it.
import '@babel/polyfill';
import { fork, take, put } from 'redux-saga/effects';
import axios from "axios";
export function* rootSaga(){
yield fork(fetch01);
yield fork(fetch02);
}
function* fetch01() {
while (true){
yield take('FETCH01_REQUEST');
axios.get('/api/members')
.then(function (response) {
// handle success
let members = response.data.data;
// yield put(get01Action(members));
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
}
}
function* fetch02() {
....
}
function get01Action(members){
return {
type: 'GET_MEMBERS',
member_id: 0,
members: members
}
}
Please give me some advice.
Thanks.
回答1:
you can use call effect to make axios call and then you will be able to use put.
right now it's not working because you are using yield inside call back of promise.
function* fetch01() {
while (true){
try {
yield take('FETCH01_REQUEST');
const response = yeild call(axios.get, '/api/members');
yield put(get01Action(response.data.data))
} catch(err) {
console.error(err)
}
}
}
回答2:
Because your generator fetch01
is sync but you're waiting an Promise
to be resovled.
yield
can not be wrapped in other functions other than generators.
You can make the generator async
, like this:
export async function* rootSaga(){
yield await fork(fetch01);
yield fork(fetch02);
}
async function* fetch01() {
while (true) {
yield take('FETCH01_REQUEST');
try {
const response = await axios.get('/api/members');
// handle success
let members = response.data.data;
yield put(get01Action(members));
} catch (error) {
// handle error
console.log(error);
} finally {
// always executed
}
}
}
来源:https://stackoverflow.com/questions/59498688/a-yield-expression-is-only-allowed-in-a-generator-body