How To Make Api Calls In Reactjs New Hook Api And Share That Across Components?
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, useEf
Solution 1:
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;
functionuseAdvice(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;
}
functionApp() {
const advice = useAdvice("https://google.com");
return<div>{advice}</div>;
}
ReactDOM.render(<App />, document.getElementById("root"));
<scriptsrc="https://unpkg.com/react@16.7.0-alpha.0/umd/react.production.min.js"></script><scriptsrc="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.production.min.js"></script><divid="root"></div>
Post a Comment for "How To Make Api Calls In Reactjs New Hook Api And Share That Across Components?"