react-state-context icon indicating copy to clipboard operation
react-state-context copied to clipboard

Long-running actions

Open jamesplease opened this issue 7 years ago • 1 comments

This library supports long-running actions right now. What this means is that you can do something like:

const createTodo = setState => newTodo => {
  setState({ loading: true });
    
  asyncCallToMakeTodo(todo)
    .then(val => {
      setState(prevState => {
        const clonedTodos = [...prevState.todos];

        return {
          todos: clonedTodos.push(newTodo),
        };
      });
    });   
};

The question is: should this functionality be removed?

The original intention of this library was to really serve as a replacement Redux for the use case of needing to share data between distant components. Long-running actions, like thunks, are an important feature of Redux, mostly for fetching data from remote places.

The argument to not support this is stems from the forthcoming Suspense update. Suspense caches are a way to store information outside of React. It may make sense for all remote data to go inside of a Suspense cache, and then only use StateContext for UI (synchronous) state that needs to be shared between distant components.

What would the API look like without this? Dan A. suggested something like getDerivedStateFromProps, where you return the new value for state. Presumably I'd be able to find a way to get a prevState value into the action with that API. I think it would actually be a pretty cool API if the Suspense story made sense.

Anyway, I'm not too sure right now!

jamesplease avatar May 29 '18 01:05 jamesplease

Note: this could still support changes derived from the previous state. Imagine this API:

disableThing = () => {
  return { active: false }
}

or...

toggleThing = () => {
  return prevState => ({
    active: !prevState.active
  })
}

jamesplease avatar Feb 13 '19 17:02 jamesplease