I’m developing a web application using React, TypeScript, and Vite. I’m encountering a SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data error in my application. The error occurs in two files: mutation.js and Register.tsx.
//api-client.ts
import { RegisterFormData } from "./pages/Register"; const API_BASE_URL = import.meta.env.VITE_API_BASE_URL; export const register = async (formData: RegisterFormData) =>{ const response = await fetch(`${API_BASE_URL}/api/users/register`,{ method: 'POST', headers: { "Content-Type": "application/json" }, body: JSON.stringify(formData) }); const responseBody = await response.json(); if (!response.ok) { throw new Error(responseBody.message); } }
// Register. tsx
const Register = () => {
const { register, watch, handleSubmit, formState: { errors } } = useForm();const mutation = useMutation(apiCliente.register,{ onSuccess: () =>{ console.log("Registration Succesful!"); }, onError: (error: Error) =>{ console.log(error.message); } }); const onSubmit = handleSubmit((data) => { mutation.mutate(data); })
It is succesfully creating and updating the user to the mongoDB that I am using, yet the onSuccess message is never displayed… Rather an error: ‘SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data’ even though the code is working ‘correctly’ I wish to understand why is this message showing and how can I fix it so the correct message can be shown.