简体   繁体   中英

How do I use a PATCH request to change a true/false value and render the change in React?

I'm making a shopping app and I want to have a button that sends a PATCH request to my db to update the value cart_status from false to true . I have the button working, but I think my syntax is off on the PATCH function. Also, if anyone is extra helpful, my img tags are not rendering the image and I don't know why (they are external image URLs if that helps).

Here is my code:

import React, { useState } from "react";

function ItemCard({ item }) {

  const [addToCart, setAddToCart] = useState(true)

  const handleAddToCart = () => {
    setAddToCart(addToCart => !addToCart)
    fetch(`/items/${item.id}`, {
      method: 'PATCH',
      headers: {
        "Content-Type": 'application/json',
      },
      body: JSON.stringify(item.cart_status)
    })
      .then(resp => resp.json())
      .then(item(setAddToCart))
  }

  return (
    <div className="card">
      <img src={item.image_url} alt={item.item_name} />
      <h4>{item.item_name}</h4>
      <p>Price: ${item.price}</p>
      <p>* {item.description} *</p>
      {addToCart ? (
        <button className="primary" onClick={handleAddToCart}>Add To Cart</button>
      ) : (
        <button onClick={handleAddToCart}>Remove From Cart</button>
      )}
    </div>
  );
}

export default ItemCard;

The results of clicking the "Add To Cart" button changes the state of the button, but does not update in the db. I also get this error message in the terminal:

Started PATCH "/items/1" for 127.0.0.1 at 2022-11-08 15:30:14 -0600
Processing by ItemsController#update as */*
  Parameters: {"_json"=>false, "id"=>"1"}
  Item Load (0.2ms)  SELECT "items".* FROM "items" WHERE "items"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/items_controller.rb:24:in `update'
Unpermitted parameters: :_json, :id
[active_model_serializers] Rendered ItemSerializer with ActiveModelSerializers::Adapter::Attributes (0.38ms)
Completed 202 Accepted in 3ms (Views: 0.7ms | ActiveRecord: 0.2ms | Allocations: 997)

Because true/false are boolean values, you can send a patch request to the rails attribute and use the bang operator "." to flip the false on the backend.

import React, { useState } from "react";

function ItemCard({ item }) {
  // console.log(item)
  const [addToCart, setAddToCart] = useState(item.cart_status)

const handleAddToCart = () => {
setAddToCart(addToCart => !addToCart)

fetch(`/items/${item.id}`, {
  method: 'PATCH',
  headers: {
    "Content-Type": 'application/json',
  },
  body: JSON.stringify({ cart_status: !item.cart_status })
})
  .then(resp => resp.json())
  .then(data => console.log(data))

  window.location.reload(false)
}



return (
<div className="card">
  <img src={item.img_url} alt={item.item_name} />
  <h4>{item.item_name}</h4>
  <p>Price: ${item.price}</p>
  <p>* {item.description} *</p>
  {addToCart ? (
    <button onClick={handleAddToCart}>Remove From Cart</button>
  ) : (
    <button className="primary" onClick={handleAddToCart}>Add To Cart</button>
  )}
</div>
);
}

export default ItemCard;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM