How to Push API Data or Values into a State Array in React 18

Last Updated on by in React JS

In this tutorial, we will show you how to request the API stepwise, extract the data from the REST API and insert it into the React array state using the useState and useEffect hooks.

This guide will teach you how to create the state that has the array data type. We will use some third-party libraries: axios and bootstrap, function component, and react hooks to push an element into a state Array in React.

React is a popular open-source JavaScript library for building user interfaces or UI components.

One of the real benefits of using React is that it pursues a declarative programming model, where front-end developers describe the desired outcome rather than the exact steps to get there.

How to Insert API Data Object’s Values into Array State in React

  • Step 1: Install React Project
  • Step 2: Install Required Dependencies
  • Step 3: Create Functional Component
  • Step 4: Add API Data in Array State
  • Step 5: Register Component in App.JS
  • Step 6: Run React Server

Install React Project

The first and foremost process is to create a new React app. Creating a new React app is easy; you have to open the terminal then start typing the following command on the terminal window.

After you execute the given command; a new app will be formed.

npx create-react-app my-react-app

Get inside the project directory:

cd my-react-app

Install Required Dependencies

We will install axios and bootstrap dependencies to help achieve our programming task.

Open the command prompt and then run the given command.

npm install axios bootstrap --legacy-peer-deps

Create Functional Component

To create a functional component in React framework, you have to define a JavaScript function that returns JSX.

You can create a components folder in the src folder, also create the Users.js file and add the given code into the file.

import React from 'react'

function Users() {
  return (
    <div></div>
  )
}

export default Users

Add API Data in Array State

In the previous step, we learned how to form a basic function component in React. Time has come to use that functional component, move into the components/Users.js file and add the code into the file.

import React, { useState, useEffect } from "react";
import axios from "axios";

function Users() {
  const Endpoint = "https://jsonplaceholder.typicode.com/users";

  const [emailList, setEmailList] = useState([]);

  const getEmailList = async () => {
    try {
      const fetchData = await axios.get(Endpoint, {
        headers: {
          authorization: "Bearer JWT Token",
        },
      });
      setEmailList(fetchData.data);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    window.addEventListener("load", getEmailList);
    return () => {
      window.removeEventListener("load", getEmailList);
    };
  }, [emailList]);

  return (
    <div className="container mt-5">
      <h2 className="mb-4">React Create Array State from REST API Examle</h2>
      {emailList.map((res) => {
        return (
          <li className="card p-3 mb-2" key={res.id}>
            <div className="card-body">
              <p className="card-text">{res.email.toLowerCase()}</p>
            </div>
          </li>
        );
      })}
    </div>
  );
}

export default Users;

Register Component in App.JS

In order to register a new component in React; you have to open the App.js file of your React project.

Then, you need to first import the new component at the top section of the file.

You can easily import the new component using the import statement something like this:

import React from 'react'
import 'bootstrap/dist/css/bootstrap.min.css'
import Users from './components/Users.js'

function App() {
  return (
    <div>
      <Users />
    </div>
  )
}

export default App;

Run React Server

Eventually, we have reached to the final segment of this tutorial. Now, you need to open your terminal or command prompt and head over to the root directory of your React project.

Then, run the following command to start the development server:

npm start

Finally, your development server will run your app on:

http://localhost:3000

How to Push API Data or Values into a State Array in React

Conclusion

In this simple and short post, we learned how to add data into an Array in a State object in React. We used certain packages and steps to append an element to a state array in React.

I am sure this short guide will help our React community.