Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set header in react API request in componentDidMount()

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>
    }
}
like image 928
the preacher Avatar asked Oct 29 '25 02:10

the preacher


1 Answers

fetch(url, {
  method: 'GET',
  headers: {
    authorization: youKEY,
    Accept: 'application/json',
  },
});
like image 195
Jim Jin Avatar answered Oct 31 '25 10:10

Jim Jin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!