threepointone / redux-react-local

local component state via redux
370 stars 21 forks source link

Dispatching "local" actions from an outside component #18

Open tnrich opened 8 years ago

tnrich commented 8 years ago

Hey there,

Is there a way to call "locally-scoped" actions from an outside component.

Say I have a @local wrapped component

And I create it in another component:

<VisualizerPlusButtons>
<DNAVisualizer identity='visualizer1'/>
<button onClick={()={ /* call a visualizer1 action here*/ }}>

<DNAVisualizer identity='visualizer2'/>
<button onClick={()={ /* call a visualizer2 action here*/ }}>

</VisualizerPlusButton>

Is it possible to do this currently?

Thanks, Thomas

threepointone commented 8 years ago

You could do this with a callback/props

@local({
  ident:'mycomp'
})
class MyComponent extends Component{
  componentWillMount() {
    this.props.onFn(this.props.$)
  }
  render() {
    // something
  }
}

/// ... later in your top level comp

render(){
  return <div> 
    <MyComponent onFn={$ => this.setState({mycomp$: $})}/>
    <button onClick={()={ dispatch(this.state.mycomp$(action)) }}/>
  </div>
}

However, I do not recommend this, the hackiness shows. Indeed, if you have a look, you can see that this isn't really a localized action then at all. Instead, why not have MyComponent listen to regular global dispatches? Can you explain more about your requirement?

threepointone commented 8 years ago

Alternately, you can render those child components as children of the 'local' component? that way $ would be in 'render scope' and it might be tidier.

tnrich commented 8 years ago

Hey @threepointone , thanks for your responses. I'm not sure redux-react-local is the tool for this specific job. I'm trying to create these redux-connected DNA visualizer components, but am struggling to allow for multiple instances of them to operate on the same page/site.

My current strategy, which allows outside components to call a specific instance's actions, is to instantiate the components with a unique key in their own files, internally wrap the actions with the unique key, and export them from the file.

Thus an outside component can import the Component, actions, selectors, etc. from the instantiated DNAVisualizer and use them like normal.

I hope that explains what I'm trying to do a bit better.

Thanks again! Thomas

gcazaciuc commented 8 years ago

Hey , Pretty old topic, but an alternative solution that allows dispatching outside actions and catching them in components reducers is redux-fractal . Hope it helps!