Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JS - How do I pass variables (parameters) to the API URL?

I have a single page that consist of two dropdown-list components; The page is only accessible upon successful authentication (valid token). Both dropdown-list consumes it's data from different JSON-API's. I have one of the dropdown list functional, but for the other, the URL to it's API requires parameters.

Example URL: http://buildingsAPI:111/api/buildings/

tested via postman with an id appended: http://buildingsAPI:111/api/buildings/abcde-abce-abc2-111-2222

sample Json:

[
    {
        "abc_buildingid": "1111-2222-3333-aaa-1111117",
        "abc_energyprogramid": "abcde-abce-abc2-111-2222",
        "siteName": "Building 1",
        "Available": false,
        "clientName": "Client 1"
    },
    {
        "abc_buildingid": "222-2222-3333-aaa-1111117",
        "abc_energyprogramid": "xyz11-abce-abc2-111-2222",
        "siteName": "Building 2",
        "Available": false,
        "clientName": "Client 2"
    },
]

...am already obtaining the token upon user authentication (localStorage), but I also need to append/pass the abc_energyprogramid as a parameter to the API URL.

...the code:

     constructor(props) {
      super(props);

      this.getToken = this.getToken.bind(this);
    }


componentDidMount() {
    const bearerToken = this.getToken();

    fetch('http://buildingsAPI:111/api/buildings/?myparam1={abc_energyprogramid}', {
     method: 'GET',
     headers: {
                'Content-type': 'application/json',
                'Authorization': `Bearer ${bearerToken}`
              },
        })
        .then(results => results.json())
        .then(buildings => this.setState({ buildings: buildings }))
      }

    getToken() {
        return localStorage.getItem('id_token');
    }

    render() {
        console.log(this.state.buildings);
        return(
            <div>
            <select className="custom-select" id="siteName">
                    { this.state.buildings.map(item =>(
                    <option key={item.siteName}>{item.siteName}</option>
                    ))
                    }
                </select>
            </div>
        );
    }

...I currently get an error:" Unhandled Rejection (SyntaxError):unexpected end of JSON input" on this line of the code: .then(results => results.json()). Could I get some help with this please?

like image 966
user1724708 Avatar asked Dec 17 '22 23:12

user1724708


1 Answers

I think the problem is the way you're referencing abc_energyprogramid

Change this:

fetch('http://buildingsAPI:111/api/buildings/?myparam1={abc_energyprogramid}')

to:

fetch(`http://buildingsAPI:111/api/buildings/?myparam1=${abc_energyprogramid}`)

Notice the back-ticks and ES6 template string literal.

like image 78
m-ketan Avatar answered Mar 07 '23 13:03

m-ketan