“Ambil data dari API di React” Kode Jawaban

Ambil data dari API di React

useEffect(() => {
    const url = "https://api.adviceslip.com/advice";

    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const json = await response.json();
        console.log(json);
      } catch (error) {
        console.log("error", error);
      }
    };

    fetchData();
}, []);
Frail Fly

cara mengambil API di komponen kelas bereaksi

//for functional components//


function MyComponent() {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);

  // Note: the empty deps array [] means
  // this useEffect will run once
  // similar to componentDidMount()
  useEffect(() => {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      )
  }, [])

  if (error) {
    return <div>Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div>Loading...</div>;
  } else {
    return (
      <ul>
        {items.map(item => (
          <li key={item.id}>
            {item.name} {item.price}
          </li>
        ))}
      </ul>
    );
  }
}
Worrisome Weevil

Bereaksi mendapatkan metode

/* React get method.  */

componentWillMount(){
    fetch('/getcurrencylist',
    {
        /*
        headers: {
          'Content-Type': 'application/json',
          'Accept':'application/json'
        },
        */
        method: "get",
        dataType: 'json',
    })
    .then((res) => res.json())
    .then((data) => {
      var currencyList = [];
      for(var i=0; i< data.length; i++){
        var currency = data[i];
        currencyList.push(currency);
      }
      console.log(currencyList);
      this.setState({currencyList})
      console.log(this.state.currencyList);
    })
    .catch(err => console.log(err))
  }
Enthusiastic Elephant

Mengambil data dengan bereaksi

// mycomponent.js
import React, { useEffect, useState} from 'react';
import axios from 'axios';

const MyComponent = () => {
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState([])

  useEffect(() => {
    const fetchData = async () =>{
      setLoading(true);
      try {
        const {data: response} = await axios.get('/stuff/to/fetch');
        setData(response);
      } catch (error) {
        console.error(error.message);
      }
      setLoading(false);
    }

    fetchData();
  }, []);

  return (
    <div>
    {loading && <div>Loading</div>}
    {!loading && (
      <div>
        <h2>Doing stuff with data</h2>
        {data.map(item => (<span>{item.name}</span>))}
      </div>
    )}
    </div>
  )
}

export default MyComponent;
serge kalaga

cara mengambil API di komponen kelas bereaksi

//for calsses components//

class MyComponent extends React.Component {
  
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };
  }

  componentDidMount() {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            items: result.items
          });
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

  render() {
    const { error, isLoaded, items } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <ul>
          {items.map(item => (
            <li key={item.id}>
              {item.name} {item.price}
            </li>
          ))}
        </ul>
      );
    }
  }
}
Worrisome Weevil

Jawaban yang mirip dengan “Ambil data dari API di React”

Pertanyaan yang mirip dengan “Ambil data dari API di React”

Lebih banyak jawaban terkait untuk “Ambil data dari API di React” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya