'What Causes 400 Bad Request In Django Graphene and NextJs Using The useMutation Hook?
I am trying to build a simple todo app using Django, Graphene and NextJs. I was able to create todos in graphiQL and postman, however when I try to create a todo in the NextJs, I get a 400 Bad Request from the server. I have tried to do same using plain ReactJs but I still get the same error. Below is the error
This is my models.py file
from django.db import models
class Todo(models.Model):
title = models.CharField(max_length=255)
completed = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
This is my todos/schema.py file
import graphene
from graphql import GraphQLError
from .models import Todo
from graphene_django import DjangoObjectType
class TodoType(DjangoObjectType):
class Meta:
model = Todo
class Query(graphene.ObjectType):
todos = graphene.List(TodoType)
def resolve_todos(self, info):
return Todo.objects.all()
class CreateTodo(graphene.Mutation):
todo = graphene.Field(TodoType)
class Arguments:
title = graphene.String()
def mutate(self, info, title):
user = info.context.user
if user.is_anonymous:
raise GraphQLError('Login to add a todo!')
todo = Todo(title=title)
todo.save()
return CreateTodo(todo=todo)
class Mutation(graphene.ObjectType):
create_todo = CreateTodo.Field()
this is my apollo-client.js file
import { ApolloClient, createHttpLink, InMemoryCache } from "@apollo/client";
const httpLink = createHttpLink({
uri: "http://localhost:8000/graphql",
});
const client = new ApolloClient({
link: httpLink,
credentials: "include",
cache: new InMemoryCache(),
});
export default client;
This is my addtodo.js file
import { useMutation } from "@apollo/client";
import { CreateTodoMutation } from "graphql/mutations";
import { useState } from "react";
import { Button, Container, Form } from "react-bootstrap";
const AddTodo = () => {
const [title, setTitle] = useState("");
const [createTodo] = useMutation(CreateTodoMutation);
const handleSubmit = (e) => {
e.preventDefault();
createTodo({ variables: { title } });
};
return (
<Container>
<h3>Add Todo</h3>
<Form onSubmit={handleSubmit}>
<Form.Group className="mb-3">
<Form.Label>Project Title</Form.Label>
<Form.Control
type="text"
placeholder="Project Title"
onChange={(e) => setTitle(e.target.value)}
/>
</Form.Group>
<Button variant="primary" type="submit">
Add
</Button>
</Form>
</Container>
);
};
export default AddTodo;
Please I'd like someone to help me figure out what I am not doing correctly here. Thanks in anticipation
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|