Fetching Data With Axios In ReactJs

Fetching Data With Axios In ReactJs

Table of contents

No heading

No headings in the article.

reactJs.png

Over the week I was trying to fetch a set of database information, I have in one of the APIs I worked on using MongoDB, Express, Mongoose, and hosted in Heroku and I ran into something I choose to call a bug, I found out that I was not able to access the data in my database.

I intentionally tried a few ways I think a novice will approach a similar problem

N/B: ReactJs useEffect hook is not promised base, that is it does not return a promise

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

const View = _ => {
    const [posts, setPosts] = useState([])

    const url = "https://mrcrudapp.herokuapp.com/api/getallposts"

    const postings = async () => {
        try{
            const res = await axios.get(url)
            setPosts(res.data.data)
        } catch (error) {
            console.log('error')
        }
    }

    useEffect( () =>  postings(), [])

After writing the logic the next thing is to map your result to loop through it.

return (
        <>
        <h1>Posts</h1>
        { posts && posts.map((myPost) =>
            <ul key={myPost._id}>
                <li>{myPost.title} : {myPost.content}</li>
            </ul>
        )}
        </>
    )

Conclusion: I hope this piece will save you time when you need it most, and please share this to help a friend.