Skip to content

Creating helper functions is unintuitive #114

@coffee-cup

Description

@coffee-cup

Sometimes when writing actions or components, it can be a good idea to split the logic that accesses the universe into reusable functions. For example, if I have the following few lines throughout my code,

import { state } from "./model";

const myAction = () => {
  const currentGameId = state.currentGame;
  const game = state.games[currentGameId];
 
  // ...
}

I may want to extract it to a function

import { state } from "./model";

const getCurrentGame = () => {
  const currentGameId = state.currentGame;
  const game = state.games[currentGameId];
  return game;
}

const myAction = () => {
  const game = getCurrentGame();
}

However, this does not work. The transpiler recognizes that the getCurrentGame function uses the state and turns in into an action. To make this work I need to pass the state varaible.

import { state } from "./model";

const getCurrentGame = (state) => {
  const currentGameId = state.currentGame;
  const game = state.games[currentGameId];
  return game;
}

const myAction = () => {
  const game = getCurrentGame(state);
}

This is fairly unintuitive because state is imported at the file level, but then needs to be passed from the action to a helper function. The example above is in an action, but the same idea applies to accessing and watching state in a component.

I am not exactly sure how to fix this, but I expect some users will get confused by this. I know @andrejak encountered this when developing the devtools, and I have encountered when just writing example apps.

Any thoughts on the above @Onurbon?

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions