Home Writing

til / ReScript: Adding new actions to an existing useReducer

Previously we updated a React component to use the useReducer hook in rescript-react. In this post, we’ll add a couple of new actions to our reducer and see how the compiler helps us with adding these new features.

1type action = Toggle | Display | Hide

We start by adding two new actions to the action type called Display and Hide. After we save we’ll get an error in the compiler saying that we haven’t covered all cases in our reducer’s pattern match. It even tells us that we are missing (Display|Hide). This is exactly what we want!

 1Warning number 8 (configured as error)
 2
 3 6  let make = () => {
 4 7    let (state, dispatch) = React.useReducer((state, action) => {
 5 8      switch action {
 6 9      | Toggle =>
 7 .  ...
 813        }
 914      }
1015    }, HideValue)
1116 
12
13You forgot to handle a possible case here, for example:
14(Display|Hide)

Let’s add the new actions to our reducer.

1switch action {
2| Display => DisplayValue
3| Hide => HideValue
4| Toggle =>
5  ...
6}

By handling both the Display and Hide case the compiler will be happy, but we don’t have anything that triggers our new actions so let’s add those next.

1<Button onClick={_ => dispatch(Display)}> {React.string("Display value")} </Button>
2<Button onClick={_ => dispatch(Hide)}> {React.string("Hide value")} </Button>

By adding two <Button> components that trigger our new actions when clicked we’ve successfully added the new functionality to our useReducer. The complete updated example looks like this

 1type state = DisplayValue | HideValue
 2
 3type action = Toggle | Display | Hide
 4
 5@react.component
 6let make = () => {
 7  let (state, dispatch) = React.useReducer((state, action) => {
 8    switch action {
 9    | Display => DisplayValue
10    | Hide => HideValue
11    | Toggle =>
12      switch state {
13      | DisplayValue => HideValue
14      | HideValue => DisplayValue
15      }
16    }
17  }, HideValue)
18
19  <div>
20    {switch state {
21    | DisplayValue => React.string("The best value")
22    | HideValue => React.null
23    }}
24    <Button onClick={_ => dispatch(Toggle)}> {React.string("Toggle value")} </Button>
25    <Button onClick={_ => dispatch(Display)}> {React.string("Display value")} </Button>
26    <Button onClick={_ => dispatch(Hide)}> {React.string("Hide value")} </Button>
27  </div>
28}

  • Loading next post...
  • Loading previous post...