DEV Community

Adebusola john
Adebusola john

Posted on

Using Firebase Authentication, Implementing Pagination after fetching data from an API (random user.me)

To get started with the project, I created a react app using npm create-react-app

  1. Create a react App
  2. create an account with firebase
  3. initialize firebase in the project

STEPS TO IMPLEMENT FIREBASE GOOGLE AUTHENTICATION.

  1. Add Firebase to your project
  2. Enable Google as a sign-in method in the Firebase console: (a) In the Firebase console, open the Auth section. (b) On the Sign in method tab, enable the Google sign-in method and click Save.

I handled the sign-in flow with the Firebase JavaScript SDK with the following these steps:
An instance of the Google provider object was created:

Image description

I also Created a component called SignInWithGoogle and SignOut in the firebase Javascript SDK with would enable me to carry out the sign-in with Popup and to signout users respectively.

Image description
In the app.js

import { signOutOfGoogle, auth } from "./firebase"
import { signInWithGoogle, GoogleAuthProvider } from "./firebase"

A button with an onCLick event would definately be needed handle the sign-in

Image description
Bind the onclick event as shown below

Image description

Inorder to check whether a user is signed in or not, I created a state using useState and then used auth.onAuthStateChange to track whether the user is signed in or not.

Image description

if the user is signed in, setSignedIn was set to true, else setSigned was set to false.

Image description

if signedIn is true, the user get redirected to the homepage, if not, the user get redirected back to the signing in page.

** TO HANDLING SIGN OUT**

I Created a button to handle sign out.
On sign out, the user would be sent back to the sign in page
<button onClick={signOut}> LogOut </button>

Bind the onclick event as shown below

const signOut = () => {
signOutOfGoogle()
.then(() => {
console.log("sign out successful")
// Sign-out successful.
}).catch((error) => {
// An error happened.
});
}

IMPLEMENTING PAGINATION AFTER FETCHING DATA FROM RANDOMUSER.ME API

To fetch data from an API
1. The following states need to be created:
data: to store the data from the API.
loading: set it to false.
error: to store the error message if there is an error.

const [data, setData] = useState([])
const [loading, setLoading] = useState(false)
const [error, setError] = useState("")

2. A function with a promise using async and await to fetch the data was created in the useEffect().

async function getData() {
const response = await fetch("https://randomuser.me/api/?page=10&results=100&seed=abc")
const result = await response.json()
return result
}
useEffect(() => {
getData()
.then(result => {
setLoading(true)
setData(result.results)
})
.catch((error) => {
setLoading(true)
setError(<h3 className="errorMessage" >No internet connection </h3>)
}
)
}, [])

To implement Pagination

Antd design was used for the pagination

To install Antd run npm i antd in the terminal

Then
import { Pagination } from "antd";

- I created the following states:

const [currentPage, setCurrentPage] = useState(1)
const [postPerPage] = useState(10)

- The variables below needs to be created
*lastPost: This gives us the index of the last post

*firstPost: This gives us the index of the first post

const lastPost = currentPage * postPerPage
const firstPost = lastPost - postPerPage
const currentPost = data.slice(firstPost,lastPost)

  • In the return() call the component below. The userdata component is where the data fetched from the API was used


return (
<div>
<Userdata data={currentPost} loading={loading} error ={error} />
<div className="pagination">
<Pagination current={currentPage} onChange={(value) =>setCurrentPage(value)} total={data.length} itemRender={itemRender} pageSize={postPerPage} />
</div>
)

Incase of an error on the page, error boundary was used to handle this error.

import { React, Component } from "react"
class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { error: null };
  }
  static getDerivedStateFromError(error) {
    return { error };
  }
  componentDidCatch(error, errorInfo) {
    console.log(error, errorInfo);
  }
  render() {

    if (this.state.error) {

      return (

        <>
          <div style={{ color: "red", textAlign: "center", display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center", minHeight: "100vh" }}>
            <h1 style={{ color: "red" }}>Something went wrong </h1>
            <p style={{ color: "black" }}> Fixing bugs, please bear with us </p>

          </div>
        </>
      )
    }

    return this.props.children;
  }
}

export default ErrorBoundary

Top comments (0)