6

I am using ustated library in my project.

In render method, I am using set like this:

render() {
    return (
            <ApiSubscribe>
                {api => (
                    <button content='CLICK ME' onClick={() => api.setMessage('RENDER CLICK')} />
                )}
            </ApiSubscribe>
    )
}

How can I call api.setMessage OUTSIDE of render? For example in componentDidMount ?

ApiSubscribe is:

export const ApiSubscribe = props => {
    // We also leave the subscribe "to" flexible, so you can have full
    // control over your subscripton from outside of the module
    return <Subscribe to={props.to || [Api]}>{props.children}</Subscribe>;
};
gaijebou
  • 71
  • 5
  • [Looking at everything that the library exports](https://github.com/jamiebuilds/unstated/blob/master/src/unstated.d.ts), I don't think you can. – Tholle Jul 28 '18 at 18:24
  • pass `api` down to a child component as a prop, and use its `componentDidMount` hook or whatever – azium Jul 28 '18 at 19:11

2 Answers2

6

Like this?

class Child extends Component {
  componentDidMount() {
    this.props.api.setMessage('hey')
  }
  render {...}
]

let Parent = () => (
  <ApiSubscribe>
    {api => <Child api={api} />}
  </ApiSubscribe>
)
azium
  • 20,056
  • 7
  • 57
  • 79
1

You can create a HOC to wrap your component, then pass the container from the HOC component to the child component in the form of props.

ttfreeman
  • 5,076
  • 4
  • 26
  • 33