React Js Context API Handle REST API Response Tutorial

In this tutorial, we will learn how to share the Rest api data globally in every component of our React app. To share the rest api data globally in our react app, we will use the Context api along with axios and bootstrap libraries.

React is a popular framework that makes its presence strong among frontend developers. It is becoming the first choice of product owners, thanks to its profound features, making it a super powerful frontend framework.

To tackle any programming problem, React offers hooks; hooks are used to manage the application state, especially when you are working with a functional component.

In this guide, we are going to talk about context api. Context is mainly used when you need to share the same data with every component your react app has.

The Context in React enables us to pass down and consume data in any component we want in our React app without the help of props object. React Context allows us to share the data or state globally in our components.

How to Manage REST API Response Globally in React with Context API

  • Step 1: Download React Project
  • Step 2: Install NPM Dependencies
  • Step 3: Build Context File
  • Step 4: Set API Response in Provider
  • Step 5: Set Provider in React Component
  • Step 6: Get Global Data via Context in Component
  • Step 7: View App on Browser

Download React Project

We need a new react application to show you how to code to clear the concept of react context api.

npx create-react-app react-blog

Install NPM Dependencies

Go to the terminal, open the terminal window, start typing the given commands, hit enter, and install the bootstrap and axios libraries together.

npm install bootstrap axios

Build Context File

Make the contexts/ folder in src/ directory, here we will create another file and give it a name PostsContext.js.

import { createContext } from 'react'

export const PostsContext = createContext([])

Set API Response in Provider

Head over to contexts directory, now this time you need to make another file we are calling it Store.js. The given below code must be added into the file.

import React, { useState, useEffect } from 'react'
import { PostsContext } from '../contexts/PostsContext'
import axios from 'axios'

function Store({ children }) {
  const [posts, setPosts] = useState([])

  useEffect(() => {
    axios
      .get('https://jsonplaceholder.typicode.com/posts')
      .then((response) => {
        setPosts(response.data)
      })
      .catch((e) => {
        console.log(e)
      })
  }, [])

  return (
    <PostsContext.Provider value={[posts, setPosts]}>
      {children}
    </PostsContext.Provider>
  )
}

export default Store

The axios library is being used here to make the get requests in response it is fetching the posts data from the server, add the state with data response to the provider property.

Set Provider in React Component

We have created the context regarding handling the api response; now, we will learn how to consume the context api response.

Head over to the App.js file, import the context and the component, then wrap the User component using Store context.

import 'bootstrap/dist/css/bootstrap.min.css'
import './App.css'

import Posts from './components/Posts'
import Store from './contexts/Store'

function App() {
  return (
    <div className="container mt-2">
      <Store>
        <Posts />
      </Store>
    </div>
  )
}

export default App

Get Global Data via Context in Component

We have to create the Posts.js file inside the components folder.

Next, import the ApiContext from the ‘../contexts/ApiContext’, also import the useContext api. We need these modules to get the rest api response through context.

Define the posts and setPosts props that we defined in the context object; use these properties to show the api response in the component.

import React, { useEffect, useContext } from 'react'
import { PostsContext } from '../contexts/PostsContext'

export default function Posts() {
  const [posts, setPosts] = useContext(PostsContext)

  useEffect(() => {}, [posts])

  return (
    <div>
      <h2 className="mb-4">
        React Update Context with REST API Call in Functional Component Example
      </h2>
      {posts.map((res, index) => {
        return (
          <div className="card mb-3" key={index}>
            <div className="card-body">
              <h5 className="card-title">{res.title}</h5>
              <h6 className="card-subtitle mb-2 text-muted">{res.body}</h6>
            </div>
          </div>
        )
      })}
    </div>
  )
}

View App on Browser

We have to test the react app for which we need to start the development server.

npm start

Open the browser and test the app with given url.

http://localhost:3000

React Js Context API Handle REST API Response Tutorial

Summary

In this extensive guide, we have learned how to use axios to get data from rest api, add api response to context provider and receive the api data in the react component using the useContext hook.