Home > Back-end >  Getting Error: Cannot read properties of undefined (reading 'map')
Getting Error: Cannot read properties of undefined (reading 'map')

Time:10-24

I am working on a project and using appwrite database for the backend. I am getting the documents array from my collection and storing in postItems array locally. This is code for getting the list of documents.I have defined getData() in a file appwrite.js and I am exporting it.

  getData: async () => {
    let promise = appwrite.database.listDocuments('61713e3e5257a');
    promise.then(function (response) {
        console.log(response.documents) //response.documents is a array
        return response.documents
    }, function (error) {
        console.log(error); // Failure
    });
},

Then is another file dashboard.js I have imported that and I am calling this to set data using useEffect like this.

const [postItems, setPostItems] = useState([])

useEffect(() => {
    const getPostData = async () => {
        try {
        
                const data = await api.getData()
                data.map((doc) => {
                    setPostItems(prevItems => [...prevItems, {
                        location: doc.location,
                        date: doc.date,
                        text: doc.experience
                    }])
                })

        } catch (error) {
            console.log(error.message);
        }
    }
    getPostData()
    console.log(postItems)
}, [])

I am not able to retrive data and getting console error as "Cannot read properties of undefined (reading 'map')" I am not able to understand what is wrong,as the getData() function is returning response.documents which is a array and I was using that to setPostItems. Would be really helpful if anyone can point out what is wrong.

CodePudding user response:

You need to return resolve see below answer

getData: async () => {
    let promise = appwrite.database.listDocuments('61713e3e5257a');
    promise.then(function (response) {
        resolve(response.documents);
        console.log(response.documents) //response.documents is a array
    }, function (error) {
        console.log(error); // Failure
    });
},

CodePudding user response:

The issue source is getData function. You have forgotten to return the data from the function. Add return promise

  • Related