Mariana Monteiro
Mariana Monteiro

Reputation: 23

Send a field conditionally in react-js axios post

I want to send a specific field (price) in the data that I will send to api using axios, but i want to send this field only if the state "new" is false.

This is an example of how i'm trying to do that, but of course it's not working! I don't know how i can do that, and if its possible.

 const [price, setPrice] = useState("");
 const [new, setNew] = useState(true);

 const url = "app/product/add";
    const sendPrice = () => {
      if (new === false) {
        price: price;
      } else {
        null;
      }
    };
    var data = {
      nome: nome,
      image: imageURL,
      images: imagesURL,
      new: new,
      sendPrice,
    };

Upvotes: 0

Views: 879

Answers (1)

Ali Baghban
Ali Baghban

Reputation: 695

Maybe this will help:

axios.post("/app/product/add", {
    price: !new ? price : undefined,
    // ... other properties
})

also:

const data = {
    // ... certain properties
};

if (!new) {
    data.price = price;
}
 
axios.post("/app/product/add", data)

Upvotes: 1

Related Questions