1

I'm using APISauce to create a post request to my server.

This works fine, and id, title and desc are variables that I pass in a function. return client.post("/workout", { userId: id, title: title, description: desc, });

description is optional, and I can't post it if the value is empty.

I can do it this way -

if (desc){
return client.post("/workout", {
        userId: id,
        title: title,
        description: desc,
    });
}else
return client.post("/workout", {
        userId: id,
        title: title,
        
});

But this is a lot of duplicate, so I just want to check if there is a more efficient way of doing this? Can I check the description field within the JSON object?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
theabrar
  • 360
  • 1
  • 6
  • 15
  • If whatever you're using doesn't automagically filter out undefined values, just create the base object, add the description if present, and have a single `post` call using the created object. There's duplication here only because you haven't separated the parameter creation from the post. – Dave Newton Mar 09 '21 at 18:55
  • I can do that way actually yeah, but it'd be a repetition nonetheless, where I'd be recreating an object, one with description and the other without. – theabrar Mar 09 '21 at 21:32
  • No, you'd create an object, and conditionally add a property to it. – Dave Newton Mar 09 '21 at 21:51

2 Answers2

2

You can write

client.post("/workout", {
    userId: id,
    title: title,
    description: desc,
});

there's no need for the check. If desc is undefined the key description will be removed when stringified to JSON.

Keimeno
  • 2,512
  • 1
  • 13
  • 34
  • I just tried this and I still got undefined const description = desc ? desc : undefined; console.log("Post workout " + description); return client.post("/workout", { userId: id, title: title, description: description, }); Even though description is undefined, I'm still getting an error because description shouldn't be empty. – theabrar Mar 09 '21 at 21:12
1

Following up with what Dave Newton suggested in the comments, it would work like the below

const body = {
  userId: id,
  title
};
if (desc) {
  body.description = desc;
}
client.post('/workout', body);

You're only creating the object once and if the property exists, you're setting it on the object.

ChrisG
  • 2,637
  • 18
  • 20