How to call a restApi in the new reactjs hook api. And reusing the data using useEffects and useState ? I want to just reuse the data across components.
import { useState, useEffect } from "react";
export default function getAdvice(url) {
fetch(`http://api.adviceslip.com/advice`)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.log(err)
}
You can create a custom hook that creates a new piece of state advice that you set when your network request has finished.
Return a function from the function given to useEffect that cancels your request when the component that uses it re-renders or the component is unmounted. You can also give your url in an array as the second argument to useEffect to only re-run the network request when the url actually changes.
Example
const { useState, useEffect } = React;
function useAdvice(url) {
const [advice, setAdvice] = useState(null);
useEffect(
() => {
const timeout = setTimeout(() => {
setAdvice(`Use ${url} to get some nice advice`);
}, 1000);
return () => clearTimeout(timeout);
},
[url]
);
return advice;
}
function App() {
const advice = useAdvice("https://google.com");
return <div>{advice}</div>;
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>
<div id="root"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With