0

I am getting the below error enter image description here

import React ,{useState,useEffect} from 'react'; import axios from 'axios';

function DataFetching() {

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

useEffect(()=>{

    axios.get('https://reqres.in/api/users')
    .then(res=>{

        console.log(res)
        setPosts(res.data)
    })
    .catch(err=>
        console.log(err) )

},[])
return (
    <div>
      
        <ul>
            {
          **  posts.map(post=><li key={post.id}>{post.email}</li>)**
            }
        </ul>
        
    </div>
);

}

export default DataFetching;

Data is successfully store in hook but map function getting an error: Posts.map is not a function

I have tried Object.values(posts).map but it is not working

1
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. Commented Nov 9, 2023 at 17:41

2 Answers 2

1

Maybe try to implement your data fetching as below. Hope it works.

  useEffect(() => {

    const fetchData = async () => {
      try {
        const response = await axios.get('https://reqres.in/api/users');
        if (response.status === 200) {
          const data = response.data;
          console.log(data);
          setPosts(data);
        } else {
          throw new Error('Network error occured.');
        }
      } catch (error) {
        console.error('Error occured while fetching data: ', error);
      }
    };

    fetchData();
  }, []);

StackBlitz example

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

1 Comment

Thank you for your response. I have tried as suggested. but it doesn't work. It shows 'The above error occurred in <DataFetching>' component. But no details about the error
0

You are getting a successful fetch result in the front end. However, res.data is not an array. Hence, the error message states .map is not a function (even though it is a prototype method on array type).

You need to console.log res.data and view the data type and verify the responses is an array.

Common cause would be forgetting to call .json() on the return json response.

Comments

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.