import { useParams } from 'react-router-dom';
import useFetch from './useFetch';

const BlogDetails = () => {
    const { id } = useParams();
    const { data: blog, error, isPending } = useFetch('http://localhost:3001/blogs/' + id);

    return (
        <div className="blog-details">
            { isPending && <div>...Loading...</div>}
            { error && <div>{error}</div>}
            { blog && (
                <article>
                    <h2>{blog.title}</h2>
                    <p>Written by {blog.author}</p>
                    <div>{blog.body}</div>
                </article>
            )}
        </div>
    );
}

export default BlogDetails;

import {useState, useEffect} from 'react';

const useFetch = (url) => {
        const [data, setData] = useState(null);
        const [isPending, setIsPending] = useState(true);
        const [error, setError] = useState(null);

    useEffect(() => {
        const abortCont = new AbortController();

        fetch(url, { signal: abortCont.signal })
            .then(res => {
                if(!res.ok){
                    throw Error('404 - data not found!');
                } 
                return res.json();
            })
            .then(data => {
                setData(data);
                setIsPending(false);
                setError(null);
            })
            .catch(err => {
                if (err.name === 'AbortError') {
                    console.log('fetch aborted');
                } else {
                    setIsPending(false);
                    setError(err.message);
                }
            })

            return () => abortCont.abort();
    }, [url]);

    return {data, isPending, error}
}

export default useFetch;

I am fairly new to react and i have spent about 2 days searching, adding and removing packages on VSCode to no avail.

I am following the Net Ninja's recent tutorial on Youtube and I am stuck on step #25. (https://www.youtube.com/watch?v=t7VmF4WsLCo&t=4s)

I have copied the code exactly but the issue seems somewhere else in React.

If anyone could help or point me in the right direction, it would be greatly appreciated.

This is the error that is giving each time I try to access the page. It is thrown for any of the pages that is not on the main page.

0

There are 0 best solutions below