skip to Main Content
async function change_status(object_id:number){
      const response = await fetch('/api/db', {
        method: 'POST',
        body: JSON.parse(`{"id":${object_id}}`)
      });
    
      if (!response.ok){
        throw new Error(response.statusText);
      }
      return await response.json();
}

I want this button to change an int in mysql

<button onClick={() => change_status(object.id)}>
    change Status
</button>

/api/db.ts

export default async function handler(req: NextApiRequest,res: NextApiResponse) {
  const data = JSON.parse(req.body);
  const object_id = data.id;
  const find_object = await prisma.objects.findFirstOrThrow({
    where: {id:object_id}
  });
  if (find_object.status == 0){
    var change = await prisma.objects.update({
      where: { id: object_id },
      data: { status:1 },
    })
  }
  else {
    var change = await prisma.objects.update({
      where: { id: object_id },
      data: { status:0 },
    })
  }
  res.json(change);
}

I get this error SyntaxError: Unexpected token o in JSON at position 1

Is there any better way to code the button or pass object_id without a JSON

2

Answers


  1. Change your fetch to

    const response = await fetch('/api/db', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ id: object_id }),
    });
        
    

    And in your api simply

    export default async function handler(req: NextApiRequest, res: NextApiResponse) {
        const { id } = req.body;
        ...
    }
    
    Login or Signup to reply.
  2. I’m just gonna drop some information about Prisma when I had these kinda problems with it.

    1 – don’t forget to use body: JSON.stringify(), (this might be the issue here)

    2 – config your header as well.

    3 – I would suggest avoiding the var keyword because of some sort of things ( like hoisting).

    4 – stick with Prisma documentation.they almost covered everything

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search