Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Where to put API call to be made on state change

Tags:

reactjs

I need to make an API call on state change in react

Which lifecycle method should I put this API call in?

componentDidUpdate(), getDerivedStateFromProps() or any other?

What is the best practice?

like image 353
Rahul Yadav Avatar asked May 19 '18 00:05

Rahul Yadav


People also ask

How make dynamic API call in react JS?

First method is, You should learn first a Context APIs in react which already mentioned in docs https://reactjs.org/docs/context.html , use it for passing data between a screen. Second method is, Always call the API at parent level component, I think its a better and easier way.

How do you handle state change in React?

To make the state change, React gives us a setState function that allows us to update the value of the state. Calling setState automatically re-renders the entire component and all its child components. We don't need to manually re-render as seen previously using the renderContent function.

How do I contact API onChange?

Just remove the second useEffect and put your API call inside onChange function like this: For a better user experience and void unnecessary calls, you should add a loading state when the user clicks on the checkbox that gets disabled while fetching the result, then checked or unchecked based on the response.


1 Answers

You should be going for componentDidUpdate() if it doesn't affect the state. getDerivedStateFromProps() mutates the state and therefore should only be used if your state relies on the nextProps the component will receive. It won't fire on your state modifications but could be used combined with componentDidUpdate() in a very few cases.

Here is a quick example using Redux of what you are willing to achieve, omitting on purpose actions, reducers and apis related files to avoid any confusion:

@connect(state => ({ searchResult: state.searchResult }))
class MassFetchingComponent extends React.Component {
    state = {
        search: '',
    }

    componentDidUpdate(prevProps, prevState) {
        if (prevState.search!== this.state.search) {
            dispatch(searchAction(this.state.search));
        }
    }

    handleChange = search => this.setState({ search })

    render() {
        return (
            <div>
                <Input value={this.state.search} onChange={this.handleChange} />
                { this.props.searchResult }
            </div>
        )
    }
}

I used an Input for the example purpose but I wouldn't recommend doing this if your state changes at a fast pace. Using sockets would be an option there.

like image 173
Eld0w Avatar answered Oct 02 '22 12:10

Eld0w