Fetch Axios error Cannot read properties React

Viewed 11

I followed some tutorial and everything is working for this guy but not for me. I use axios to try to fetch some simple data, but I get a Cannot read properties error in the console and it is not fetching and not displaying data.

I think my setup is pretty basic, so I really wonder what I have done wrong here. My PHPStorm isn't flagging any typos so I'm not sure I'm doing this right.

Here is my DataFetching.js code:

import React, {useState, useEffect} from "react";
import axios from "axios";

function DataFetching(){
    const [post, setPost] = useState();
    const [id, setId] = useState(1)
    const [idFromButtonClick, setIdFromButtonClick] = useState(1)

const handleClick = () => {
    setIdFromButtonClick(id)
}

useEffect(() => {
    axios.get(`https://jsonplaceholder.typicode.com/posts/${idFromButtonClick}`)
        .then(res => {
            console.log(res);
            setPost(res.data)
        })
        .catch(err => {
            console.log(err)
        })
}, [idFromButtonClick])

return (
    <div>
        <input type="text" value={id} onChange={e => setId(e.target.value)} />
        <button type="button" onClick={handleClick}>Fetch</button>
        {post.title}
    </div>
)
}

export default DataFetching

The error I'm getting is:

DataFetching.js:27 Uncaught TypeError: Cannot read properties of undefined (reading 'title') at DataFetching (DataFetching.js:27:1)

Is there anyone that can point me in the right direction?

1 Answers

The initial post value is undefined. You can display the post like this {post?.title} so, if it's not undefined, no errors are thrown.

Check the optional chaining operator here

Related