Skip to content

Instantly share code, notes, and snippets.

@Jahans3 Jahans3/consume-update.js
Last active Dec 10, 2018

Embed
What would you like to do?
Updating and consuming our state
export default function SomeCount () {
return (
<StateConsumer>
{({ state, setState }) => (
<>
<p>
Count: {state.count}
</p>
<button onClick={() => setState({ count: state.count + 1 })}>
+ 1
</button>
<button onClick={() => setState({ count: state.count - 1 })}>
- 1
</button>
</>
)}
</StateConsumer>
);
}
@danilowoz

This comment has been minimized.

Copy link

danilowoz commented Dec 10, 2018

Hey @Jahans3, I've read your article and I just found two little mistakes in your gist:

  1. Adjacent JSX elements must be wrapped in an enclosing tag, maybe use a fragment or a div;
  2. count in the setState is not defined;

So, updating that:

export default function SomeCount() {
  return (
    <StateConsumer>
      {({ state, setState }) => (
+        <React.Fragment>
          <p>Count: {state.count}</p>
-          <button onClick={() => setState({ count: count + 1 })}>+ 1</button>
-          <button onClick={() => setState({ count: count - 1 })}>- 1</button>
+          <button onClick={() => setState({ count: state.count + 1 })}>+ 1</button>
+          <button onClick={() => setState({ count: state.count - 1 })}>- 1</button>
+        </React.Fragment>
      )}
    </StateConsumer>
  )
}

Cheers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.