Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

Fetching data with React hooks and Axios

// use-fetch-data.js
import { useEffect, useState} from 'react';
import axios from 'axios';

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

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

    fetchData();
  }, []);

  return {
    data,
    loading,
  };
};

export default useFetchData;
Comment

react hook for fetching data with axios

//mycomponent.js
import React from 'react';
import useFetchData from './hooks/use-fetch-data.js'

const MyComponent = () => {
  const {
    data,
    loading,
  } = useFetchData();

  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

PREVIOUS NEXT
Code Example
Javascript :: how to create a pop up in middle screen javascript 
Javascript :: find an object from array of objects javascript 
Javascript :: change on select with javascript 
Javascript :: try catch async await 
Javascript :: navlink activestyle not working 
Javascript :: set selected option jquery 
Javascript :: dropzone remove error file 
Javascript :: how to create a new angular project in visual studio code 
Javascript :: jquery data 
Javascript :: nestjs allow origin 
Javascript :: jest render target container is not a dom element 
Javascript :: js store regex in variable and combine 
Javascript :: bootstrap 4 modal popup remote url 
Javascript :: javascript onclick event 
Javascript :: logic operators in js 
Javascript :: upi id regex 
Javascript :: Factorialize a Number 
Javascript :: javascript function to strikethrough text 
Javascript :: java script remove last charecter from the string 
Javascript :: data table is not a function in vue 
Javascript :: javascript import 
Javascript :: Nestjs download 
Javascript :: react context api with hooks 
Javascript :: chart.js clear data 
Javascript :: switch to window in testcafe 
Javascript :: fibonacci recursion 
Javascript :: js map key value 
Javascript :: loop through nested json object typescript 
Javascript :: SyntaxError: await is only valid in async function 
Javascript :: leaflet tile service 
ADD CONTENT
Topic
Content
Source link
Name
1+6 =