“Daten mit React abrufen” Code-Antworten

Daten von API in React abrufen

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

Reagieren Sie Methode

/* 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

Daten mit React abrufen

// 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

Ähnliche Antworten wie “Daten mit React abrufen”

Fragen ähnlich wie “Daten mit React abrufen”

Weitere verwandte Antworten zu “Daten mit React abrufen” auf JavaScript

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen