javascript - Uncaught TypeError: Cannot read properties of undefined (reading 'url') - Stack Overflow

I'm new to react js, I'm getting Uncaught TypeError: Cannot read properties of undefined (rea

I'm new to react js, I'm getting Uncaught TypeError: Cannot read properties of undefined (reading 'url') error due to fetching images map. If I use data already on the file, it works fine, but if I have to fetch the data, it creates This error. This is what is tried. please let me know how to fix this error.

 const THECATAPI = ''

  const [catList, setCatList] = useState([])


       const axiosPosts = async () => {
      try {
        const response = await axios(THECATAPI)
        setCatList(response.data)
      } catch (error) {
        console.log('erroRRRR');

      }
    };



 
   // return 
<div>

 
    {
        catList.map((obj, i) => (
            <div >
                <img src={obj['image']['url']} alt='loading' />
            </div>
    }

</div>

I'm new to react js, I'm getting Uncaught TypeError: Cannot read properties of undefined (reading 'url') error due to fetching images map. If I use data already on the file, it works fine, but if I have to fetch the data, it creates This error. This is what is tried. please let me know how to fix this error.

 const THECATAPI = 'https://api.thecatapi./v1/breeds'

  const [catList, setCatList] = useState([])


       const axiosPosts = async () => {
      try {
        const response = await axios(THECATAPI)
        setCatList(response.data)
      } catch (error) {
        console.log('erroRRRR');

      }
    };



 
   // return 
<div>

 
    {
        catList.map((obj, i) => (
            <div >
                <img src={obj['image']['url']} alt='loading' />
            </div>
    }

</div>
Share Improve this question asked May 1, 2022 at 12:54 Ganesh MBGanesh MB 1,1792 gold badges17 silver badges31 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

Since you are accessing the nested value from the array, there may be some cases, the value might not be presented. You can use optional chaining while accessing the nested field. You can simply change your block of code like this.

{catList.map((obj, i) => (
  <div key={obj?.id}>
    <img src={obj?.image?.url} alt="loading" />
  </div>
))}

Attaching the sandbox here.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745464886a4628872.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信