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

[RFC] Effect just belong to store for react-model v4 #185

Open
EzrealPrince opened this issue Dec 13, 2021 · 2 comments
Open

[RFC] Effect just belong to store for react-model v4 #185

EzrealPrince opened this issue Dec 13, 2021 · 2 comments
Assignees
Labels
✨Feature Request New feature or request

Comments

@EzrealPrince
Copy link

EzrealPrince commented Dec 13, 2021

Sometimes we want to watch a store state and do some effects

like this, by easy-peasy https://easy-peasy.vercel.app/docs/api/effect-on.html

export default createStore({
  items: [],
  saving: false,
  setSaving: action((state, payload) => {
    state.saving = payload;
  }),
  addItems: action((state, payload) => {
    state.items.push(payload);
  }),
  stateChange: unstable_effectOn(
    [(state) => state.items],
    async (actions, change) => {
      const [items] = change.current;
      actions.setSaving(true);
      await todosService.save(items);
      actions.setSaving(false);
    }
  )
});

in the react-model v4, we usually write it like this

export const { useStore } = createStore(() => {
  const [todoItems, setTodoItems] = useModel<string[]>([])
  const [saving, setSaving] = useModel<boolean>(false)

  const addItems = useCallback((item) => setTodoItems(todoItems => todoItems.push(item)), [])
  
  //  it will register repeatedly
  //  so may be provide a new store effect hook just execute once
  useEffect(() => {
    setSaving(true);
    await todosService.save(todoItems);
    setSaving(false);
  }, [todoItems])

  return {
    todoItems,
    saving,
    addItems
  }
})
@catee
Copy link

catee commented Aug 8, 2022

any update?

@catee
Copy link

catee commented Aug 31, 2022

@EzrealPrince It works for me. But I don't think it's the right way for solving this problem.

import { useModel, createStore } from 'react-model'

import axios from 'axios'

let needRequest = true

const useStore = () => {
  const [options, setOptions] = useModel({})

  if (needRequest) {
    axios(url, { data: {} }).then((data) =>
      setOptions(data)
    )
  }

  needRequest = false

  return options
}

// Model Register
export const { useStore: useOptions } = createStore(useStore)

Looking forward to @ArrayZoneYour 's reply ^_^

@ArrayZoneYour ArrayZoneYour self-assigned this Sep 14, 2022
@ArrayZoneYour ArrayZoneYour added the ✨Feature Request New feature or request label Sep 14, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
✨Feature Request New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants