Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Warning: Cannot update a component from inside the function body of a different component

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?

like image 323
Smith Dwayne Avatar asked Mar 04 '20 13:03

Smith Dwayne


1 Answers

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 } } 
like image 102
Dominic Avatar answered Sep 21 '22 06:09

Dominic