Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Previous Value within connect callback. #22

Open
loeiks opened this issue Jul 8, 2024 · 1 comment
Open

Previous Value within connect callback. #22

loeiks opened this issue Jul 8, 2024 · 1 comment

Comments

@loeiks
Copy link

loeiks commented Jul 8, 2024

Can we get the previous value of a key when working with connect? If not it would be great to have a feature like that to compare values to perform an update or not. Currently I'm handling it manually.

Like in @ changed

store.on("@changed", (state, change) => {
    // we can get the changes
})

I would expect something like this for connect:

connect("key", (previousState, state) => {
   // we can compare states
})

or

connect("key", (previousValueOfKey, state) => {
   // we can compare values only not all state
})

I think both would work.

@shoonia
Copy link
Owner

shoonia commented Nov 22, 2024

Hello @loeiks

The connect is a method to render your data. You shouldn't check your state in connect callback, only the render logic.

connect('name', (state) => {
  $w('#name').value = state.name;
});

The idea of split your app: 1) state manage layer and 2) render layer. The connect will run only if the state is changed. The changing/check/update state you should manage in the modules.

store.on('add/item', (state, newItem) => {
  if (state.items.length > 100) {
    return; // the state won't be update, if you return nothing
  }
  
  return {
    items: [...state.items, newItem],
  };
});

In the module you have the current state and it should return partial of state that you want to update or undefined if you don't want to update state.

state.on('your/event', (state, data) => {
  const previousState = { ...state };
  const nextState = { ...state, ...data };
  
  if (businessLogic(previousState, nextState)) {
    return nextState;
  }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants