I am using a reusable generator function to make the call to REQUEST/SUCCESS/FAILURE actions. I then have another generator to call that function but I would like to get some kind of feedback and raise another action. Not sure how to explain it, here is an example of what I want to do:
/* in actions/index.js */
export const login = {
request: () => action(constants.LOGIN.REQUEST),
success: (response) => {
try {
jwtDecode(response.auth_token);
} catch (e) {
return action(constants.LOGIN.FAILURE,
{ payload: { error: {
status: 403,
statusText: 'Invalid token',
} } });
}
return action(constants.LOGIN.SUCCESS, { payload: { response } });
},
failure: error => action(constants.LOGIN.FAILURE, { payload: { error } }),
};
/* sagas/index.js */
function* postEntity(entity, apiFn, body) {
yield put(entity.request());
const { response, error } = yield apply(null, apiFn, body);
if (response) {
yield put(entity.success(response));
} else {
yield put(entity.failure(error));
}
}
function* postLogin(action) {
yield postEntity(login, api.login, [action.payload.email, action.payload.password]);
// How can I get some kind of feedback (succeed or not) from postEntity here and do a put(something_else) if succeeded?
}
export default function* rootSaga() {
yield takeLatest(constants.LOGIN_USER, postLogin);
}
Any feedback is really appreciated.
Thanks!
Have postEntity return a value like response or true/false. Then in postLogin check for that value.
const result = yield postEntity(login, api.login, [action.payload.email, action.payload.password]);
then check the value of result and fire success/failure events accordingly like you did in postEntity.
if(result) {yield put(successCreator())} else { ...}
Related
I have this custom hook which fetches the query.me data from graphql. The console.log statement shows that this hook is running a number of times on page load, but only 1 of those console.logs() contains actual data.
import { useCustomQuery } from '../api-client';
export const useMe = () => {
const { data, isLoading, error } = useCustomQuery({
query: async (query) => {
return getFields(query.me, 'account_id', 'role', 'profile_id');
},
});
console.log(data ? data.account_id : 'empty');
return { isLoading, error, me: data };
};
I then have this other hook which is supposed to use the id's from the above hook to fetch more data from the server.
export const useActivityList = () => {
const { me, error } = useMe();
const criteria = { assignment: { uuid: { _eq: me.profile_id } } } as appointment_bool_exp;
const query = useQuery({
prepare({ prepass, query }) {
prepass(
query.appointment({ where: criteria }),
'scheduled_at',
'first_name',
'last_name',
);
},
suspense: true,
});
const activityList = query.appointment({ where: criteria });
return {
activityList,
isLoading: query.$state.isLoading,
};
};
The problem I am facing is that the second hook seems to call the first hook when me is still undefined, thus erroring out. How do I configure this, so that I only access the me when the values are populated?
I am bad with async stuff...
In the second hook do an early return if the required data is not available.
export const useActivityList = () => {
const { me, error } = useMe();
if (!me) {
return null;
// or another pattern that you may find useful is to set a flag to indicate that this query is idle e.g.
// idle = true;
}
const criteria = { assignment: { uuid: { _eq: me.profile_id } } } as appointment_bool_exp;
...
I upgraded from old redux saga to the latest version and the following stopped working.
function* loadAlbumPhoto({ entity }, entityId) {
try {
const { accessToken: at } = yield select(state => state.user.info);
let {
data: { data: albums }
} = yield call(API.loadAlbumByEntityId, { entityName: entity, entityId, type: PHOTO });
if (!albums.length) {
const options = {
entityId,
entityName: entity,
title: PHOTO,
type: PHOTO
};
yield call(API.createAlbum, options);
({ data: { data: albums } } = yield call(API.loadAlbumByEntityId, { entityName: entity, entityId, type: PHOTO }));
}
const [album] = albums;
const { data: { data: photos } } = yield call(API.loadPhotosByAlbumId, album.id);
return yield photos.map(function* (photo) {
const src = yield getPhotoUrl(photo.uploadData.path, at);
return {
src,
uploadId: photo.uploadId,
photoId: photo.id
};
});
} catch (err) {
console.log(err);
return [];
}
}
function* getPhotoUrl(path, at) {
try {
const userPhoto = yield API.userPhoto(path, at);
return userPhoto;
} catch (err) {
/* eslint-disable no-console */
console.log(err);
/* eslint-enable no-console */
}
return "";
}
As you can see i am trying to return array from loadAlbumPhoto but my problem is that i need to call getPhotoUrl function which is also a generator function.
The problem is that the result of loadAlbumPhoto is Array of generators and not Array of values. It happened since my upgrade to the last version of redux and redux saga.
Already tried to use yield* but not working or i don't know how to use it.
yield*
I would do a bit of refactoring of the anonymous generator and then convert your yield to use all: https://redux-saga.js.org/docs/api/#alleffects---parallel-effects
function* getPhotoDetails(photo) {
const src = yield getPhotoUrl(photo.uploadData.path, at);
return {
src,
uploadId: photo.uploadId,
photoId: photo.id
};
}
function* loadAlbumPhoto({ entity }, entityId) {
// similar up to yield photos.map...
return yield all(photos.map(photo => call(getPhotoDetails, photo)));
// similar after
}
Can we use dispatch inside action creators and what purpose do they serve inside action creators ?
Here is a sample modified code from codebase .
export default function xyz(data) {
const url = ;
return function (dispatch) {
dispatch(
a()
);
callApi(url, REQUESTS.POST, HEADERS, data).then((response) =>{
dispatch(
b(data)
);
}).catch((error) => {
dispatch(
c(error.toString())
);
});
};
}
// this returns a type (an object)
export function a() {
return {
type: xyzzzz
};
}
Similarly we have b and c returning either type or say objects .
Yes, you can dispatch multiple actions in an action.
I usually put a dispatch on an asychnronous action like this
function action() => {
return async (dispatch) => {
let payload;
dispatch('before-request');
try {
await someAsyncProcess();
payload = { status: 'success' };
} catch (err) {
payload = { status: 'failure' };
}
dispatch('after-request', payload);
};
}
I created a rootSaga in sagas.js as
function* fetchStuff(action) {
try {
yield put({type: 'INCREMENT'})
yield call(delay, 1000)
yield put({type: 'DECREMENT'})
const highlights = yield call(API.getStuff, action.data.myObject);
} catch (e) {
yield put({type: 'FETCH_STUFF_FAILED', message: e});
}
}
export default function* rootSaga() {
yield takeEvery('INIT_LOAD', fetchStuff);
}
I am calling the INIT_LOAD after thirdParty.method:
class myClass extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.load();
}
load = () => {
this.init = () => {
this.myObject = thirdParty.method(event => {
const action = {
type: 'INIT_LOAD',
payload: {
myObject: this.myObject
}
};
store.dispatch(action);
});
};
this.init();
};
render() {
return (
<div id="render-here" />
);
}
Passing the this.myObject in the action that is dispatched does not trigger the saga. If I change the action payload to a string, like the following, the saga is triggered.
const action = {
type: 'INIT_LOAD',
payload: {
myObject: 'this.myObject'
}
};
Why am I unable to pass this.myObject but a string is ok?
UPDATE: It is not a saga issue. I replicated the same issue with just plain redux. The rootReducer as
export default function rootReducer(state = initialState, action) {
switch (action.type) {
case 'INIT_LOAD':
return Object.assign({}, state, { myObject: action.payload.myObject });
default:
return state;
}
}
As I mentioned in the comment below, assigning it to an object Obj does not change the issue
let Obj = {};
...
load = () => {
this.init = () => {
Obj.myObject = thirdParty.method(event => {
const action = {
type: 'INIT_LOAD',
payload: {
myObj: Obj
}
};
store.dispatch(action);
});
};
this.init();
};
UPDATE2
I cleaned the code up & simply dispatched an action in the component that triggers the saga. Inside the saga is where I do the init(). I ran into another issue where the object that I was trying to save in the redux store has active socket sessions (which were given me cross-domain issues). Although I didn't solve my original problem, not storing a socket object made my problem go away.
I am trying to use redux saga to make the async calls simultaneously as I load the page... but only the loadPositions() is being called. anyone have an idea why? I think it has to do with a race condition. Please correct me.
const fetchPositions = () => {
return fetch(POSITIONS_API_ENDPOINT).then(function (response) {
return response.json().then(function (results) {
return results.map(function (p) {
return {
position: p.position,
platformId: p.platform_id
}
})
})
})
};
const fetchBanners = () => {
return fetch(BANNER_API_ENDPOINT).then(function (response) {
return response.json().then(function (results) {
return results.map(function (p) {
console.log(p)
return {
banner_id: p.banner_id,
type: p.image.type,
width: p.image.width
}
})
})
})
};
export function* loadBanners() {
try {
const banners = yield call(fetchBanners);
yield put({type: "BANNERS_LOADED", banners})
} catch (error) {
yield put({type: "BANNERS_LOAD_FAILURE", error: error})
}
}
export function* loadPositions() {
try {
const positions = yield call(fetchPositions);
yield put({type: "POSITIONS_LOADED", positions})
} catch (error) {
yield put({type: "POSITION_LOAD_FAILURE", error: error})
}
}
export function* rootSaga() {
yield [
loadBanners(),
loadPositions()
]
}
Try this:
Start the initial parallel loading by firing the ON_LOAD_START action
Make all your requests in parallel using the yield [] syntax and fire the appropriate actions with result data.
Root saga, compose all of your sagas:
export default function* rootSaga() {
yield fork(watchOnLoad);
}
Watcher saga, waits for action ON_LOAD_START before kicking of the worker saga:
function* watchOnLoad() {
// takeLatest will not start onLoad until an action with type
// ON_LOAD_START has been fired.
yield* takeLatest("ON_LOAD_START", onLoad);
}
Worker saga, actually makes all the requests in parallel and fires the success or error actions with relevant result data:
export function* onLoad() {
try {
const [banners, positions] = yield [
call(fetchBanners),
call(fetchPositions)
]
yield put({type: "ON_LOAD_SUCCESS", banners, positions})
} catch (error) {
yield put({type: "ON_LOAD_ERROR", error})
}
}