2

When I did a console.log(response.data), it returned 2 datasets namely post and user:

 const [dbdata,setDBData] = useState([])

useEffect(async() => {
        const response = await Axios.get('http://localhost:5000/api/posts/allpost', {withCredentials:true})
    setDBData(response.data)
    console.log(response.data)
    }, [])


{post: Array(2), user: Array(1)}
post: (2) [{…}, {…}]
user: [{…}]

So when I tried dbdata.post.map(), it says map() is a not function. What I am missing here? Many thanks in advance and greatly appreciated.

7
  • I'm guessing that the data is empty from the server. Check console.log on the response.data. Commented Dec 2, 2020 at 9:11
  • there are data. {post: Array(2), user: Array(1)} Commented Dec 2, 2020 at 9:13
  • Please post the minimal code for people to help. from the snippet we are not sure which one threw error. dbdata.post.map() is not present in the code you shared. Commented Dec 2, 2020 at 9:16
  • Define your state like this - const [dbdata,setDBData] = useState({post: [], user: []}) Commented Dec 2, 2020 at 9:17
  • Thanks. So how do I solves this? Sorry am still not an experience a lot of scenarios. Commented Dec 2, 2020 at 9:19

1 Answer 1

5

Issue

Initial state is an empty array []

const [dbdata,setDBData] = useState([]);

so dbdata.post and/or dbdata.user are both undefined if you are attempting to render and map them on the initial render.

dbdata.post.map(...) // <-- throws error since dbdata.post undefined

Solution

Provide correct initial state so the initial render has valid state to access and map.

const [dbdata,setDBData] = useState({ post: [], user: [] });
Sign up to request clarification or add additional context in comments.

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.