Search code examples
reasonreason-react

action has wrong type in ReasonReact reducer


I'm trying to create a simple todo app, this is an input component and I need a reducer to update the state of the input. This code is throwing the error - This pattern matches values of type action but a pattern was expected which matches values of type unit => string

For some reason it expects action to be unit => string and I have no idea why. Can anyone help?

type state = string;
type action = 
  | InputChange(string);

let component = ReasonReact.reducerComponent("Input");

let make = (~onSubmit, _children) => {
  ...component,
  initialState: () => "",
  reducer: action => 
    switch (action) {
    | InputChange(text) => ReasonReact.Update(text)
    },
  render: ({state: todo, send}) =>
    <input
      className="input"
      value=todo
      type_="text"
      placeholder="What do you want todo"
      onChange={e => send(ReactEvent.Form.target(e)##value)}
      onKeyDown={
        e =>
          if (ReactEvent.Keyboard.key(e) == "Enter") {
            onSubmit(todo);
            send(() => "");
          }
      }
    />,
};

Solution

  • The type of action is inferred by the use of send in render, where you pass it () => "", a function of type unit => string. It should be send(InputChange("")).

    You're also missing the state argument on reducer. It should be reducer: (action, state) => ..., or reducer: (action, _state) => ... to avoid the unused warning, since you're not using it.