Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

custom hook react

//helper>useFetch.jsx
import {useEffect,useState} from 'react'

const useFetch = (url) => {

    const [data,setData] = useState([])

    useEffect(()=>{
      fetch(url).then(res => res.json()).then(data => {
        setData(data);
      }).catch(e=>console.log(e.message));
    },[])
  
  return data
}

export default useFetch

//App.jsx
import useFetch from './helper/useFetch.jsx'
const App = () => {

  const data = useFetch('https://fakestoreapi.com/products')

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

export default App
Source by www.geeksforgeeks.org #
 
PREVIOUS NEXT
Tagged: #custom #hook #react
ADD COMMENT
Topic
Name
6+4 =