Skip to main content

Fetch Data

Displaying 1 - 2 of 2

Fetching data using inbuilt fetch API

All modern browsers come with an inbuilt fetch Web API, which can be used to fetch data from APIs. 
In this tech article, I will to show you how to do fetching data from the JSON Server APIs.

DrupalVIP technical notebook & support

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

const UsingFetch = () => {
  const [users, setUsers] = useState([])

  const fetchData = () => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(response => {
        return response.json()
      })
      .then(data => {
        setUsers(data)
      })
  }

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

  return (
    <div>
      {users.length > 0 && (
        <ul>
          {users.map(user => (
            <li key={user.id}>{user.name}</li>
          ))}
        </ul>
      )}
    </div>
  )
}

export default UsingFetch

Fetch and display data from API in React js

When you develop an application, you will often need to fetch data from a backend or a third-party API. 
In this article, I will try to go through the process of fetching and displaying data from a server using React Fetch.

DrupalVIP technical notebook & support

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

function handleClick() {
    alert('You clicked node ');
}

export default function RWTaskIssues({nodeid}) {        
    const FetchAPI = '/rwtask/issues?task=' + nodeid + '&op=get';
    console.log("api fetch: " + FetchAPI);
    
    const [issues, setIssues] = useState([]);
    const fetchData = () => {
        fetch(FetchAPI)
            .then(response => {
                return response.json();
            })
            .then(response => {
                console.log("response data: " + response.data.items);
                setIssues(response.data.items);
            });
    };

    useEffect( () => {
        fetchData();
    }, []) ;   
    
    console.log("issues data: " + issues);
    
    return (
        <div className="block block-layout-builder block-field-blocknoderwtaskfield-rwtask-issue">
            <h2 className="block-title">תיאור הבעיה</h2>
            <div className="block-content">               
                {issues.length > 0 && (
                    <div className="field field-name-field-rwtask-issue field-type-text-long field-label-hidden field-items">
                        {issues.map(item => (
                            <div key={item.key} className="field-item" dangerouslySetInnerHTML={{__html: item.value}} />
                        ) ) }
                    </div>
                )}
                <button onClick={handleClick}>
                    Edit
                </button>            
            </div>
        </div>
    );        
}