[SOLVED] I want to pull the headers in the data in the useFetch function I created


This Content is from Stack Overflow. Question asked by Emre Can Akyol

I want to pull the headers in the data in the useFetch function I created.
What can I write instead of the following function (data + title).
//const {data, loading} = useFetch(data + title);


import React from 'react';
import { View, Text, ActivityIndicator } from 'react-native';
import useFetch from '../../components/Hooks/useFetch';
import styles from './Detail.style';

const Detail = ({route}) => {
    const {title} = route.params;
    const {data, loading} = useFetch(data + title);

    if (loading) {
        return <ActivityIndicator/>

    return (
        <View style={styles.container}>
            <View style={styles.body_container}>
                <Text style={styles.title}>{data.title}</Text>
                <Text style={styles.description}>{data.description}</Text>
                <Text style={styles.programType}>{data.programType}</Text>
                <Text style={styles.releaseYear}>{data.releaseYear}</Text>

export default Detail;


You should be able to access the headers using response.headers
So, once you have a response object, it is just a matter of accessing the iterator and storing it in a format suitable for you. (Feel free to change it)

import { useState, useEffect } from "react";

const useFetch = () => {
    const [data, setData] = useState([]);
    const [headers, setHeaders] = useState({})
    const [loading, setLoading] = useState(true);

    useEffect(() => {
    }, []);

    const fetchData = async () => {
        try {
            const response = await fetch('https://gist.githubusercontent.com/hknclk/5710c4adb791755b31ccde6777f04bd2/raw/19954b5d84f476a1d691ce43e4319292893cc27a/sample.json');
            const json = await response.json();

            let headers = {};
            for (const kvp of response.headers.entries()) {
              headers[kvp[0]] = kvp[1]
              console.log(`${kvp[0]}: ${kvp[1]}`);

        } catch (error) {

    return {data, headers, loading}

export default useFetch;

This Question was asked in StackOverflow by Emre Can Akyol and Answered by Marco It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?