Where Should I Make Ajax And Api Calls In React.js Function Components?
I've been learning more about React.js function components and have started transitioning one of my React.js applications to use them instead of the standard react components. In m
Solution 1:
This is what React hooks gives us - ways to do side effects in functional components:
https://reactjs.org/docs/hooks-effect.html
from the doc page:
If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.
for example:
importReact, { useState, useEffect } from'react';
functionExample() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:useEffect(() => {
//do an ajax call here
});
return (
<div><p>You clicked {count} times</p><buttononClick={() => setCount(count + 1)}>
Click me
</button></div>
);
}
Solution 2:
You can use react-pure-lifecycle to add lifecycle functions to functional components.
Example:
importReact, { Component } from'react';
import lifecycle from'react-pure-lifecycle';
const methods = {
componentDidMount(props) {
//ajax call here
}
};
constChannels = props => (
<h1>Hello</h1>
)
exportdefaultlifecycle(methods)(Channels);
Post a Comment for "Where Should I Make Ajax And Api Calls In React.js Function Components?"