1

I follow the example in https://scotch.io/tutorials/create-a-custom-usefetch-react-hook, to perform a fetch. All works.

I change it slightly to make a POST with 'Accept': 'application/json' and 'Content-Type': 'application/json' as per https://stackoverflow.com/a/29823632. However, no matter how I post, it is still of Text/Html context type.

const useFetch = (url, body) => {
    const [response, setResponse] = React.useState(null);
    const [error, setError] = React.useState(null);

    React.useEffect(() => {
        const FetchData = async () => {
            try {
                const method = "POST"
                const headers = {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                };
                const options = {
                    method,
                    headers
                };
                if (body) options.body = JSON.stringify(body);
                const res = await fetch(url, options);
                const json = await res.json();
                setResponse(json);
            } catch (error) {
                setError(error);
            }
        };
        FetchData();
    }, []);
    return { response, error };
};

export default useFetch

What did I do wrong?

Elye
  • 53,639
  • 54
  • 212
  • 474

1 Answers1

0

I'd say the answer depends on your request URL. Is your endpoint only capable of returning type text/html? What resource are you requesting?

Parker Tailor
  • 1,290
  • 13
  • 12
  • It is returning JSON output. I also need to past JSON data through the payload. It's actually calling the graphql using normal REST POST https://graphql.org/learn/serving-over-http/ – Elye Nov 26 '19 at 06:12