Skip to content

Instantly share code, notes, and snippets.

@Jahans3
Last active December 10, 2018 17:41
Show Gist options
  • Save Jahans3/d5de84f02f0a41e98b18401b0e2ad51c to your computer and use it in GitHub Desktop.
Save Jahans3/d5de84f02f0a41e98b18401b0e2ad51c to your computer and use it in GitHub Desktop.
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
Copy link

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