I am using Redux with Class Components in React. Having the below two states in Redux store.
{ spinner: false, refresh: false }
In Parent Components, I have a dispatch function to change this states.
class App extends React.Component { reloadHandler = () => { console.log("[App] reloadComponent"); this.props.onShowSpinner(); this.props.onRefresh(); }; render() { return <Child reloadApp={this.reloadHandler} />; } }
In Child Component, I am trying to reload the parent component like below.
class Child extends React.Component { static getDerivedStateFromProps(props, state) { if (somecondition) { // doing some redux store update props.reloadApp(); } } render() { return <button />; } }
I am getting error as below.
Warning: Cannot update a component from inside the function body of a different component.
How to remove this warning? What I am doing wrong here?
For me I was dispatching to my redux store in a React Hook. I had to dispatch in a useEffect
to properly sync with the React render cycle:
export const useOrderbookSubscription = marketId => { const { data, error, loading } = useSubscription(ORDERBOOK_SUBSCRIPTION, { variables: { marketId, }, }) const formattedData = useMemo(() => { // DISPATCHING HERE CAUSED THE WARNING }, [data]) // DISPATCHING HERE CAUSED THE WARNING TOO // Note: Dispatching to the store has to be done in a useEffect so that React // can sync the update with the render cycle otherwise it causes the message: // `Warning: Cannot update a component from inside the function body of a different component.` useEffect(() => { orderbookStore.dispatch(setOrderbookData(formattedData)) }, [formattedData]) return { data: formattedData, error, loading } }
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