ReasonJun

React : Request AJAX within the component (two way) 본문

Frontend/React

React : Request AJAX within the component (two way)

ReasonJun 2023. 6. 14. 18:10
728x90

Requesting AJAX (Asynchronous JavaScript and XML) within a component refers to making asynchronous HTTP requests to a server or API directly from a component in a web application. This allows you to fetch data or interact with the server without causing a full page refresh.

 

To perform AJAX requests within a component, you can use the built-in fetch API or popular libraries such as Axios or jQuery's $.ajax. Here's an example using the fetch API within a React component:

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

const MyComponent = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('https://api.example.com/data');
        const jsonData = await response.json();
        setData(jsonData);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []);

  return (
    <div>
      {data ? (
        <ul>
          {data.map(item => (
            <li key={item.id}>{item.name}</li>
          ))}
        </ul>
      ) : (
        <p>Loading data...</p>
      )}
    </div>
  );
};

export default MyComponent;

There are two approaches to implement in-list filtering.

  • Filtering within a component : To import complete list data and filter lists into search terms.

https://codesandbox.io/s/filter-by-client-forked-ucb5rc?file=/src/App.js 

 

filter by client (forked) - CodeSandbox

filter by client (forked) by YouJun-IWON using react, react-dom, react-scripts

codesandbox.io

Pros : Can reduce the frequency of ‘http’ requests.

Cons : Since there is a lot of data in the memory of the browser(client), the burden of the client increases.

 

  • Filtering from the outside of a component
import { useEffect, useState } from "react";
import "./styles.css";
import { getProverbs } from "./storageUtil";

export default function App() {
  const [proverbs, setProverbs] = useState([]);
  const [filter, setFilter] = useState("");
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("언제 effect 함수가 불릴까요?");
    const result = getProverbs(filter);
    setProverbs(result);
  }, [filter]);

  const handleChange = (e) => {
    setFilter(e.target.value);
  };

  const handleCounterClick = () => {
    setCount(count + 1);
  };

  return (
    <div className="App">
      필터
      <input type="text" value={filter} onChange={handleChange} />
      <ul>
        {proverbs.map((prvb, i) => (
          <Proverb saying={prvb} key={i} />
        ))}
      </ul>
      <button onClick={handleCounterClick}>카운터 값: {count}</button>
    </div>
  );
}

function Proverb({ saying }) {
  return <li>{saying}</li>;
}

Pros : The client does not have to think about implementing filtering.

Cons : Frequent HTTP requests occur, and the server handles filtering, so the server is burdened.

728x90
Comments