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

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 :: sum function in javascript 
Javascript :: how to display image in html from json object 
Javascript :: jquery datepicker enable year selection 
Javascript :: math module js 
Javascript :: before in javascript 
Javascript :: pass parameter to javascript function onclick 
Javascript :: react pdf 
Javascript :: react filter array 
Javascript :: multiple forms formData js 
Javascript :: string to svg react 
Javascript :: react composition 
Javascript :: jquery button click confirm and validate before submit 
Javascript :: array last element 
Javascript :: google script get sheet size 
Javascript :: javascript array destructuring 
Javascript :: how to dynamically populate pdf with pdfmake node 
Javascript :: how to search for react icons on vscode 
Javascript :: promise javascript 
Javascript :: jquery onchange get element 
Javascript :: jquery class 
Javascript :: amcharts 
Javascript :: js setinterval run immediately 
Javascript :: javascript regular expression 
Javascript :: custom eslint config react hooks 
Javascript :: visual studio code json to one line 
Javascript :: Find Dubplicate In Array of Object 
Javascript :: react hook state not updating immediately 
Javascript :: reduce in javascript 
Javascript :: node get path of current file 
Javascript :: documentelement javascript 
ADD CONTENT
Topic
Content
Source link
Name
3+6 =