0.2.2 • Published 4 years ago

ndelitski-effector-next v0.2.2

Weekly downloads
3
License
MIT
Repository
github
Last release
4 years ago

Effector Next

Commitizen friendly

Installation

npm install effector-next

or yarn

yarn add effector-next

effector-next requires effector, effector-react to be installed

@effector/babel-plugin is necessary if you do not want to manually name the units

Usage

  1. To load the initial state on the server, you must attach withFork wrapper to your _document component

    import Document from "next/document";
    import { withFork } from "effector-next";
    
    import { serverStarted } from "../model";
    
    const enhance = withFork({ debug: false, unit: serverStarted });
    
    export default enhance(Document);
  2. To get the initial state on the client and drop it into the application, you must attach withHydrate wrapper to your _app component

    import { withHydrate } from "effector-next";
    import App from "next/app";
    
    const enhance = withHydrate();
    
    export default enhance(App);
  3. To bind events/stores on the server to the scope, add aliases from effector-react toeffector-react/ssr in next.config.js

    const { withEffectoReactAliases } = require("effector-next/tools");
    
    const enhance = withEffectoReactAliases();
    
    module.exports = enhance({});
  4. Replace import from "effector" to "effector-next"

    - import { createEvent, forward } from "effector"
    + import { createEvent, forward } from "effector-next"

Example

// model.js
import { forward, createEvent, createStore, createEffect } from "effector-next";

export const serverStarted = createEvent();

const effect = createEffect({
  handler() {
    return Promise.resolve({ name: "someServerName" });
  },
});

export const $data = createStore(null);

$data.on(effect.done, (_, { result }) => result);

forward({
  from: serverStarted,
  to: effect,
});
// pages/index.jsx
import React from "react";
import { useStore } from "effector-react";

import { $data } from "../model";

export default function HomePage() {
  const data = useStore($data);

  return (
    <div>
      <h1>Data preloaded on the server:</h1>
      {JSON.stringify(data)}
    </div>
  );
}

export default enhance(MyDocument);

Configuration

The withFork accepts a config object as a parameter:

  • unit : unit called on the server to set the initial state
  • debug (optional, boolean) : enable debug logging

Server payload

When the unit passed to withFork is called, the object will be passed as a payload:

  • cookies : parsed cookies
  • headers : request headers
  • pathname : path section of URL
  • query : query string section of URL parsed as an object.
0.2.2

4 years ago

0.2.1

4 years ago