Using Firebase Authentication, Implementing Pagination after fetching data from an API (random user.me)
Published: 2023-01-08 18:45:23

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

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u8bkfvqdr0zdaca1kva9.jpeg)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mvi89vcusd15v90nx3t8.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t1aa815wce92tag3i0qj.png)
Bind the onclick event as shown below

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/byfy6k148gp8ry2s4bf5.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h4kf04hl9pyz65fi29ul.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bxh3hr5yxvyi9doi0a79.png)

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
```