Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

fetch data from api in 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();
}, []);
Comment

how to fetch api in class component react

//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>
    );
  }
}
Comment

Fetching data with React

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

how to data fetch in react

import {useEffect,useState} from 'react'

const App = () => {
  const [data,setData] = useState([])

  useEffect(()=>{
    fetch('https://fakestoreapi.com/products').then(res => res.json()).then(data => {
      setData(data);
    }).catch(e=>console.log(e.message));
  },[])

   console.log(data);

  return (
    <div>
      {data.map(i => <p key={i.id}>{i.title}</p> )}
    </div>
  )
}

export default App
Comment

how to fetch api in class component react

//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>
      );
    }
  }
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: import axios 
Javascript :: javascript call function on click give element id 
Javascript :: give div event listener functional component 
Javascript :: javascript check collision 
Javascript :: jquery validation plugin 
Javascript :: scroll to top in jquery 
Javascript :: vim total number of lines 
Javascript :: adonis attach 
Javascript :: get unchecked checkbox jquery 
Javascript :: 413 payload too large nodejs 
Javascript :: javascript check date greater than today 
Javascript :: make link disabled in angular 
Javascript :: javascript wait for function to return value 
Javascript :: javascript css left 
Javascript :: redirect page using javascript 
Javascript :: Valid intents must be provided for the Client 
Javascript :: color p5js 
Javascript :: puppeteer stealth 
Javascript :: enzyme debug 
Javascript :: jquery get document scrolltop 
Javascript :: javascript ip 
Javascript :: pick random from array 
Javascript :: show hide boxes using radio button selection jquery 
Javascript :: next js fallback 
Javascript :: disable input field using jquery 
Javascript :: jquery get location of user 
Javascript :: javascript show localstorage size 
Javascript :: loop through object js 
Javascript :: next js navigation to other page in a function 
Javascript :: TypeError: getComputedStyle(...).getPropertyValue is not a function 
ADD CONTENT
Topic
Content
Source link
Name
7+3 =