Home > database >  How to fetch specific JSON data using an ID (React Hooks)
How to fetch specific JSON data using an ID (React Hooks)

Time:02-22

I want to get a specific item from a json using its unique ID but with the function that I have created I do not get any data. This is the function:

export function getPost(id) {
  return fetch("http://localhost:3004/edit/" id)
    .then(data => data.json())
}

And this is the page where I want to print the item. The ID comes from another page and it's shown in the url, where I get it thanks to useParams:

interface IPost {
    id: number;
    title: string;
    author: string;
    content: string;
}

const Edit: React.FC = () => {
    const [post, setPost] = useState<IPost>();

    const {id} = useParams();

    // Not working
    getPost(id)
    .then(items => {
        setPost(items)
    })

    return (
        <div className="containerHomepage">
            <form className="formulari">
                <div className="containerBreadCrumb">
                    <ul className="breadCrumb">
                        <li>Posts</li>
                        {/* THIS SHOWS AN ERROR */}
                        {post.author}
                    </ul>
                </div>

                <div className="containerTitleButton">
                    <input
                        className=""
                        type="text"
                        placeholder='Post title'
                        name="title"
                        // onChange={handleInputChange}
                    ></input>
                    <button
                        className="button"
                        type="submit"
                    >Save</button>
                </div>

                <div className="containerEdit">
                    <input
                        className="editAuthor"
                        type="text"
                        placeholder='Author'
                        name="author"
                        // onChange={handleInputChange}
                    ></input>
                    <input
                        className="editContent"
                        type="textarea"
                        placeholder='Content'
                        name="content"
                        // onChange={handleInputChange}
                    ></input>
                    {/* <div className="errorEmpty">{error}</div> */}
                </div>

            </form>
        </div>
    );
};


// ========================================

export default Edit;

Throws an error in "{post.author}", and I guess that it's something wrong with my function "getPost".

CodePudding user response:

Since you initialize post to undefined:

const [post, setPost] = useState<IPost>();

trying to access properties of it will throw:

{post.author}

Your TypeScript should have warned you about this - it's good to fix TypeScript warnings before running apps for real to avoid runtime errors. Check that the object exists before trying to access properties on it.

{post?.author}

There's no issue with your getPost function, except for the fact that you should probably only call it once, when the component mounts, not every time it re-renders.

useEffect(() => {
  getPost(id).then(setPost);
}, []);

I'd also recommend not ignoring errors - catch them to avoid unhandled rejections.

useEffect(() => {
  getPost(id).then(setPost).catch(handleError);
}, []);
  • Related