Home > Blockchain >  React response data is undefined when rendered
React response data is undefined when rendered

Time:04-03

In my react app I am fetching data from API, the response object is as below:-

posts {
  total: 3,
  data:[
        {some data},
        {some data},
        {some data}
       ] }

The data is rendered using a map() function.

but whenever the page renders the data is displayed only once. After the first render when the page is re-rendered the data array is undefined (in console.log).

code for component:-

const function = () => { 
 
 const dispatch = useDispatch();

  const { posts, isSuccess } = useSelector((state) => state.posts);


  useEffect(() => {
    dispatch(getPosts());
   
  }, [dispatch]);


  return (
    <>
      
       
          <div className="main-content">
          
                {posts.data.map((post) => (
                  <Post
                    postId={post._id}
                    postSubject={post.subject}                    
                  />
                ))}
              </div>
            
           
    </>
  );
}

export default function;


CodePudding user response:

You can try this before map function.

   <React.Fragment>
      {typeof object.data === typeof [] && (
        <React.Fragment>
          {object.data.map((obj, index) => {
            return <React.Fragment>return some code .....</React.Fragment>;
          })}
        </React.Fragment>
      )}
    </React.Fragment>

I hope it's work

  • Related