tip

There is the official Next.js bindings package - @effector/next. Follow its documentation to find out, how to integrate Next.js with effector.

There are situations when we need to get values from external libraries through callbacks. If we directly bind events, then we will face the loss of the scope. To solve this problem, we can use scopeBind.

We have some external library that returns us the status of our connection. Let’s call it an instance in the store and call it $service, and we will take the status through an event.

import { createEvent, createStore } from "effector";

const $connectStatus = createStore("close");
const connectEv = createEvent();

sample({
  clock: connectEv,
  targt: $connectStatus,
});

Next, we need to create an effect, within which we will connect our event and service.

import { attach, scopeBind } from "effector";

const connectFx = attach({
  source: {
    service: $service,
  },
  async effect({ service }) {
    /**
     * `scopeBind` will automatically derive current scope, if called inside of an Effect
     */
    const serviceStarted = scopeBind(connectEv);

    return await service.on("service_start", serviceStarted);
  },
});

After calling our effect, the event will be tied to the scope and will be able to take the current value from our service.

Contributors