Search code examples
reactjsgraphapollo

Error: Response not successful: Received status code 400


The application uses apollo server and react in the frontend. In the backend I use apollo server. The request works via the Playground and Postman and I don't get any errors. Queries in the frontend without parameters also work perfectly. When I make a mutation in the frontend, I get the following error error: Response not successful: Received status code 400. When print debugging in the backend, I also don't get any args. In the Web-console: The XHR POST http://localhost:4000/ contains the following request: {"variables":{},"query":"mutation ($title: String!, $dotColor: String!) {\n newStack(title: $title, dotColor: $dotColor) {\n stackID\n title\n dotColor\n __typename\n }\n}\n"}

src/queries/queries.js

import { gql } from "@apollo/client";

[...]

const newStackMutation = gql`
  mutation($title: String!, $dotColor: String!) {
    newStack(title: $title, dotColor: $dotColor) {
      stackID
      title
      dotColor
    }
  }
`;

[...]

export {[...], newStackMutation};

src/components/NewStack.js

import { useMutation } from "@apollo/client";
import { newStackMutation } from "../queries/queries";
import { useState } from "react";

export default function NewStack() {
  const [newStack] = useMutation(newStackMutation);
  const handleNewStackSubmit = (e) => {
    //newStack({variables}); actually I would pass the variables from the setState here
    newStack({ title: "Test", dotColor: "red" });
  };
  return (
    <div>
      <form onSubmit={handleNewStackSubmit}>
      [...]
          <button type="submit" />
        </div>
      </form>
    </div>
  );
};

Solution

  • Ah, you know what its probably because you need to add the name of the mutation

    const newStackMutation = gql`
      mutation newStack($title: String!, $dotColor: String!) {
        newStack(title: $title, dotColor: $dotColor) {
          stackID
          title
          dotColor
        }
      }
    `;// Notice the `newStack` next to `mutation`, that should work
    

    Also this

    newStack({variables: { title: "Test", dotColor: "red" }});