0

Im writing a web page in React.

I call to API and everything is working well. I have a property of 'Error' in my json response from the request.

the end of the component:

 const er = data.Error
        return <p> {er} </p>

and I can see the correct error message on the web page.

but when I'm write something like this:

if(data.Error.includes('specific error message...')
        return <p> 'specific error message...' </p>

I got the following message:

TypeError: Cannot read properties of undefined (reading 'includes')

the all component:

import React from "react";
import Movie from "./Movie";
import { useEffect, useState } from 'react';


export default function MovieList({searchValue}) {
    const [data, setData] = useState([])
    //Onmount
    useEffect(() => {
        async function init() {
      //API Calls- request data from the server
        const response = await fetch('http://www.omdbapi.com/?apikey=ca0aa516&s=' + searchValue);
        const body = await response.json();
        setData(body);
     }
    init()
    
     }, [searchValue])

     console.log(data)
    if(data.Search) {
        return (
            <div className="container-fluid movie-app" >
                <div className="row">        
                    { 
                          data.Search.map((movie) => {    
                            return (
                                <Movie link={movie.Poster} />
                                )
                        })
                    } 
                </div>
            </div>
              
        )
    }
   
    const er = data.Error
    
        return <p> {er} </p>
    
  }

6
  • please put the full code here to help you Commented Dec 18, 2021 at 10:49
  • it says that Error is undefined! Commented Dec 18, 2021 at 10:55
  • @HDM91 Using the optional chain or checking the Error before using the includes can fix the error Commented Dec 18, 2021 at 10:58
  • @Farzaneh Pichlou you right but i want to know why it was undefined Commented Dec 18, 2021 at 11:08
  • @HDM91 You don't have any error and your request is successful Commented Dec 18, 2021 at 11:15

1 Answer 1

1

You have to make an edit:

if(data?.Error?.includes('specific error message...'))

or

if(data.Error && data.Error.includes('specific error message...'))

Sign up to request clarification or add additional context in comments.

2 Comments

work! thank you! maybe you have an explain why it's solved the problem?
@amit Welcome, you are accessing the nested property at the same time the Error key is undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.