Home > Enterprise >  React undefined is not an object
React undefined is not an object

Time:05-20

Have popular errors when I see TypeError: undefined is not an object (evaluating 'posts.map') , but I don't understand where is wrong, can you help me and say where is wrong?

  const [posts, setPosts] = useState([]);

        const options = {
            method: 'GET',
            headers: {
                'X-RapidAPI-Host': 'mdblist.p.rapidapi.com',
                'X-RapidAPI-Key': 'key'
            }
        };
        
        fetch('https://mdblist.p.rapidapi.com/?i=tt0012195', options)
            .then(response => response.json())
            .then(res => {
                setPosts(res.data);
            })
                    
   
    {
        posts.map(item => {
            <div>{item.title}</div>
        })
    }
    

Update

CodePudding user response:

Maybe at this moment the data is not received, try

conditional rendering

Change your code like following:

 posts && posts.map(item => {
                <div>{item.title}</div>
            })
  • Related