operators for array-stores #147
Replies: 4 comments 5 replies
-
Possible problem: sampleForEach({
source: runTransactionGroup,
target: runTransaction, // run all transactions from group one-by-one
})
sample({
clock: runTransaction // clock will be triggered only for last triggered element from the group
greedy: true // unless sample is greedy
}) UPD: not reproducible with effect as a runner https://share.effector.dev/BF1iOwSy |
Beta Was this translation helpful? Give feedback.
-
Another implementation: export function each<S, T = S>(config: {
source: Event<S[]> | Store<S[]>;
clock?: Unit<any>;
target?: Unit<T>;
fn?: (value: S) => T;
}): Unit<T> {
const target = config.target ?? createEvent<V>();
const fn = config.fn ?? mapper;
const fx = createEffect((list) => list.forEach((value) => target(fn(value))));
sample({
source: config.source,
clock: config.clock ?? config.source,
target: fx,
});
return target;
}; |
Beta Was this translation helpful? Give feedback.
-
A while ago, I was asking for a solution to "call event for each item" // Calls runTransaction payload.length times
const runTransactions = repeat({
times: payload => payload.length,
fn: (payload, idx) => payload[idx], // idx is based on the current iteration.
// We can also return undefined here to skip call for a specific item
target: runTransaction
})
// Will call runTransaction with each item
runTransactions([1, 2, 3])
// We can also add support for stores/plain values
const doFiveRequests = repeat({
times: 5,
target: doRequest
})
// Will call doRequest 5 times with the same payload ('cause no fn was provided)
doFiveRequests("something")
// Real example: plan X reminders with time interval
// depending on reminders count set by user
const saveReminders = repeat({
source: $date,
times: $count,
fn: (date, idx) => ({
date: date.addMinutes(5 * idx)
}),
target: createReminder
})
// Will call createReminder $count times with data from fn
saveReminders() Note that |
Beta Was this translation helpful? Give feedback.
-
Here is a bit unrelated to patronum proposal, what if we would add some container for tagging multiple target in declare const loadItemsByIds: Event<string[]>:
declare const loadItemById: Event<string>:
forward({ from: loadItemsByIds, to: eachOf(loadItemById) })
sample({ clock: loadItemsByIds, target: eachOf(loadItemById), fn.... })
// etc.
Imho, such code is also easy to read - I want to disclaimer: just starting using effector |
Beta Was this translation helpful? Give feedback.
-
At the moment there is no option in basic effector api to do something like
call that event on every item from this array in store or in event payload
Idea is to create operator which is something like this:
Live example:
https://share.effector.dev/vx6hm1il
Possible use case:
Beta Was this translation helpful? Give feedback.
All reactions