4

The problem I'm struggling with is I have an API with an access key and I don't know how to setup the header inside the component with that API access key. I'm using a default fetch random user API in example below but I want to know how and where should I add that header with access key?

import React from 'react';

export default class FetchRandomUser extends React.Component {

    async componentDidMount() {
        const url = "https://api.randomuser.me/"
        const response = await fetch(url)
        const data = await response.json();
        this.setState({ person: data.results[0], loading: false })
    }

    render() {
        return <div>
            {this.state.loading || !this.state.person ? (<div>Loading...</div>) : (<div>{this.state.person.name.first}</div>)}
        </div>
    }
}

2 Answers 2

5
fetch(url, {
  method: 'GET',
  headers: {
    authorization: youKEY,
    Accept: 'application/json',
  },
});
Sign up to request clarification or add additional context in comments.

Comments

0

This is how you can pass your api key in url https://randomapi.com/api/qcol88t8?key=TCGJ-8B0M-33L6-UX5Q;`

Code

export default class FetchRandomUser extends React.Component {
  state = {
    loading: true,
    person: {}
  };

  async componentDidMount() {
    const url = `https://randomapi.com/api/qcol88t8?key=TCGJ-8B0M-33L6-UX5Q`;
    const response = await fetch(url);
    const data = await response.json();
    this.setState({ person: data.info, loading: false });
  }

  render() {
    return (
      <div>
        {this.state.loading || !this.state.person ? (
          <div>Loading...</div>
        ) : (
          <h2>{this.state.person.user.username}</h2>
        )}
      </div>
    );
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.