Search code examples
reactjsgraphqlapolloreasonreason-react

How to use refetchQueries with reason-apollo?


I'm using reason-apollo and having problems trying to setup refetchQueries. My setup is very similar to the swapi example here. I have a listing and a form to add a new item via a mutation. After the mutation succeeds, I want to refetch the items in the listing. My code for creating a new item looks like this (skipping some of the irrelevant ui code):

module CreateFilm = [%graphql
  {|
  mutation createFilm($name: String!, $favourite: Boolean!, $rating: Int!, $ratedOn: DateTime!) {
      createFilm(name: $name, favourite: $favourite, rating: $rating, ratedOn: $ratedOn) {
          id
          favourite
          name
          rating
      }
  }
|}
];

module CreateFilmMutation = ReasonApollo.CreateMutation(CreateFilm);

type state = {
  favourite: bool,
  rating: int,
};

type action =
  | ToggleFavourite
  | UpdateRating(int);

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

let make = _children => {
  ...component,
  initialState: () => {favourite: true, rating: 5},
  reducer: action =>
    switch (action) {
    | ToggleFavourite => (
        state => ReasonReact.Update({...state, favourite: ! state.favourite})
      )
    | UpdateRating(newRating) => (
        state => ReasonReact.Update({...state, rating: newRating})
      )
    },
  render: ({state, send}) => {
    let now = Js.Date.make() |> Js.Date.toISOString |> Js.Json.string;
    let newFilm =
      CreateFilm.make(
        ~name="Temporary test",
        ~rating=state.rating,
        ~favourite=state.favourite,
        ~ratedOn=now,
        (),
      );
    <CreateFilmMutation>
      ...(
           (mutation, _result) =>
             <form
               onSubmit=(
                 event => {
                   ReactEventRe.Synthetic.preventDefault(event);
                   mutation(
                     ~refetchQueries=[|"allFilms"|],
                     ~variables=newFilm##variables,
                     (),
                   )
                   |> ignore;
                 }
               )>
               <input
                 className="toggle"
                 _type="checkbox"
                 checked=state.favourite
                 onChange=((_) => send(ToggleFavourite))
               />
               ("is favourite" |> ReasonReact.string)
               <input _type="submit" value="Submit" />
             </form>
         )
    </CreateFilmMutation>;
  },
};

The film gets successfully added and I can see it in the listing (which is using the allFilms query) when the page is refreshed. But refetchQueries does not seem to have any effect. My backend is using graph.cool, similar to the swapi example in the docs. Any help is appreciated, thanks!


Solution

  • The problem was not with the mutation, but with the query I wanted to refetch - it was missing its graphql operation name 🤦‍♂️