Search code examples
javascriptnode.jsaxioslinkedin-api

Saving data from JSON end point


I am trying to map over the returned json and save the id into profile/profiles. However it does not seem to be mapping over the the data correctly, id: ${ profile.id } this bit needs to be changed? Any help is much appreciated.

Is their a online tool that can help with me this?

API request:

  // Grabs company data from the json url
  private getProfiles() {
    let config = {
      headers: {'Authorization':'Bearer AQVVEqNXTWVYPpPYivKNWVO8jsTx2eveV3kBg'}
    }
    axios
      .get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
      .then(response => 
          response.data.map(profile => ({
            id: `${ profile.id }`
         }))
        )
        .then(profiles => {
          this.setState({
            profiles
          });
        })
      // We can still use the `.catch()` method since axios is promise-based
      .catch(error => this.setState({ error, isLoading: false }));
  }

Json data returned:

{
    "localizedLastName": "King",
    "id": "fm0B3D6y3I",
    "localizedFirstName": "Benn"
}

When I console log the response.data enter image description here


Solution

  • If the only data returned from your endpoint is the JSON you posted, then you don't have an array to map over.

    You have a single object.

    I've never used the axios library before, but looking at the source code response.data should be the JSON-parsed responseText from the XHR request:

    https://github.com/axios/axios/blob/4f189ec80ce01a0275d87d24463ef12b16715d9b/lib/adapters/xhr.js#L51-L53

    https://github.com/axios/axios/blob/4f189ec80ce01a0275d87d24463ef12b16715d9b/lib/defaults.js#L61

    And now I see that you have posted response.data and it matches what I'd expect.

    With that in mind I'd suggest handling it like this:

     // Grabs company data from the json url
      private getProfiles() {
        let config = {
          headers: {'Authorization':'Bearer AQVVEqNXTWVYPpPYivKNWVO8jsTx2eveV3kBg'}
        }
        axios
          .get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
          .then(response => ({
                id: profile.id
             }))
            .then(profiles => {
              this.setState({
                profiles
              });
            })
          // We can still use the `.catch()` method since axios is promise-based
          .catch(error => this.setState({ error, isLoading: false }));
      }
    

    What you're getting back is a single profile though. If you need profiles to be an array you'll need to put the response in an array.