Danny
Danny

Reputation: 337

TypeError: Cannot read property 'map' of undefined. React js

Hey guys I am new to react js and I am getting this error TypeError: Cannot read property 'map' of undefined, I tried console.log of the object and it is showing all the results but I am not able to display it in the browser as this error pops up. What can be the reason?

const search = 'api/posts/search'
const [appState, setAppState] = useState({
    search: '',
    posts: [],
});

const [error, setError] = useState('')

useEffect(() => {
    axiosInstance.get(search + '/' + window.location.search)
        .then((res) => {
            const allPosts = res.data;
            setAppState({ posts: allPosts });
            setError('');
            // console.log(res.data);
        })
        .catch((errors) => {
            setAppState({});
            setError('Something went wrong!')
        })
}, [setAppState])




{/* console.log(appState.posts.results) */}
{appState.posts && appState.posts.results.map((post) => {
      return (
               <div key={post.id}>
                  <h5>{post.title}</h5>
               </div>
      )}
})}

Thanks

Upvotes: 0

Views: 299

Answers (1)

Mohammad Faisal
Mohammad Faisal

Reputation: 2363

Well it seems you are trying to render from posts before getting the results yet. you can change your rendering code to

{appState.posts && appState.posts.results && appState.posts.results.map((post) => {
      return (
               <div key={post.id}>
                  <h5>{post.title}</h5>
               </div>
      )}
})}

Upvotes: 1

Related Questions