2

I want to conditionally append different headers to my request object. I don't want to use if/else.

The following ... gives syntax error expression expected.

I've looked at some other examples on SO but they don't seem to work. I just can't get my syntax right.

headers is some object that comes from function args which may or may not exist.

What is the correct way to write this?

    const req = {
      meta: {
        id: "asd123"
      }
    }

    {...req.meta, ...( headers ? headers : { "Content-Type": "application-json" })}

I want my output to look something like this

    const req = {
      meta: {
        id: "asd123"
      }
      headers: {
        ContentType: "application-json",
      }
    }
asus
  • 1,427
  • 3
  • 25
  • 59

5 Answers5

2

You need req as complete object for spreading and a new headers property.

result = { ...req, headers: (headers || { "Content-Type": "application-json" }) };

If you like to use short hand properties, you need to update headers first.

headers = headers || { "Content-Type": "application-json" };
result = { ...req, headers };
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • import React, { Component } from "react"; class Testt extends Component { obj = { user1: "vijay", imageUrl: "https://picsum.photos/id/1/200/300" }; render() { return (
    {/*

    ; // error : '...' expected */}

    ); } } export default Testt; why does it ask me to use spread operator at h1 tag but not for img tag ? @Nina Scholz
    – vijay kiran reddy Oct 12 '20 at 14:50
  • @vijaykiranreddy, i have no idea of react. – Nina Scholz Oct 12 '20 at 14:51
1

If you just typed this line

{...req.meta, ...( headers ? headers : { "Content-Type": "application-json" })}

Into your IDE, this is not an expression. You should assign it to a variable or use it in another way. The ternary part seems fine to me.

genius42
  • 243
  • 1
  • 6
1

Probably

{...req, headers: headers || { "Content-Type": "application-json" }}

req.headers will be assigned to headers if it exists or { "Content-Type": "application-json" } if not.

mmfallacy
  • 186
  • 8
0

As header is coming as a funtion's args - you can first default initialize that header with undefined. Then just try this code -

if header is present then simply destructure it - {...req.meta, ...( headers ? {headers} : { "Content-Type": "application-json" })}

Subhadeep
  • 149
  • 5
0

Code Readability has its own importance. Thus, I find below solution as most appropiate:

req.headers = headers || { "Content-Type": "application-json" }

Also, You can use Nullish coalescing operator '??' as below :

req.headers = headers ?? { "Content-Type": "application-json" }

But, '??' is a recent addition to the language. Old browsers may need polyfills.