Tips for preventing Parent Component from Re-rendering after dispatching updated Redux properties?

Good evening everyone,

I've encountered an error with one of my components. The error message reads:

Cannot update a component (GameBase) while rendering a different component (ExistingGame). To locate the bad setState() call inside...

I'm not exactly sure how to troubleshoot and fix this issue.

In my code, I am conditionally rendering the ExistingGame component based on Redux properties within the GameBase component, like this:-

if (gameReducer.registered){
    return(
        <>
            <ExistingGame />
            { goBackIcon }
        </>
    )   
}

The gameReducer.registered is set through a dispatch function triggered by an onClick event in a list rendered within the GameBase component:-

const ActiveGameList = () => (

        <table><tbody>
          {activeGamesArray.map(activeGame => (
            ...
            <td key={`join${activeGame.gameId}`} className="joinGame"> <IconContext.Provider value={{ size:20 }}><div className='joinGameIcon' onClick={()=>{ joinTheGame(activeGame) }}><ImUserPlus /></div></IconContext.Provider></td>
            </tr>
          ))}
        </tbody></table>
      );

    return(
        <>
            <h1>Existing games</h1>
            <h3>Select game to join:</h3>
            <ActiveGameList />
            <br/>
            { goBackIcon }
        </>
    )

The function causing the issue is joinTheGame, defined as follows:-

const joinTheGame = async (activeGame) => {
    let gameInfo = {gameId:activeGame.gameId, gameName: activeGame.gameName, bankerPlayerNumber: activeGame.bankerPlayerNumber, forename: activeGame.firstName, surname: activeGame.lastName, gameLive: activeGame.gameLive };
    
    // Fetch details for selected game before proceeding
    await client.query({
        query: GAME_PLAYER_DETAILS,
        fetchPolicy: "network-only",
        variables: {gameId:gameInfo.gameId}
      })
      .then(result => {
           let players = result.data.allGameMoneyPlayers.nodes;
           gameInfo.players = players;

            if (joinLiveGame){
                dispatch(reJoinGame(gameInfo));  
            } else if (joinPendingGame){
                dispatch(joinGame(gameInfo));
            }
        });
}

From my research, it seems that placing the state-changing call within a useEffect hook might solve the problem. However, attempting to wrap the reJoinGame dispatch in a useEffect results in a "React Hook 'useEffect' cannot be called inside a callback" error.

If anyone could offer guidance on how to address this issue, I would greatly appreciate it. Thank you.

Answer №1

If you happen to come across this page with similar issues, I discovered that the problem stemmed from my redux reducer in the GameBase component. In managing the user's interaction with the game at the GameBase level, I had something like this:

const gameReducer = (state = [], action) => {
switch(action.type){
    case "SET_GAME":
        return {
            registered: true,
            inGame: true,
            game: {...action.payload}
        }
    case "JOIN_GAME":
            return {
                registered: false,
                inGame: true,
                game: {...action.payload}
            }
    case "REJOIN_GAME":
        return {
            registered: true,
            inGame: true,
            game: {...action.payload}
        }    
    ...

    default: return state
}

The issue was that the SET_GAME action was also triggered by the ExistingGame component, causing a re-render due to changes in the game data. This led to an unexpected behavior.

To resolve this, I created a separate reducer solely for handling game data through SET_GAME and updated my dispatch accordingly in the ExistingGame component.

In essence, it was a human error! It's important to note that if you encounter this issue, it may not necessarily involve searching for setState() calls in your child components.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Prop type validation failed: Material-UI requires either the `children`, `image`, `src`, or `component` prop to be specified in ForwardRef(CardMedia). Please make sure to provide

Every time I attempt to post a new Scream on my page, the image, title, and content of the card are not displaying until after I refresh the page. It is showing failed prop types error message indicating that values from prop types are not being obtained i ...

Although server-side rendering is utilized with react-query, JSON data continues to be displayed in the network tab

As per my understanding, the only way to conceal a JSON return from an API call is through server rendering. I have implemented this on all pages using Next.js; however, the network tab still displays a JSON with my data on pages where useInfiniteQuery and ...

What is the correct way to iterate through a list of images fetched with getStaticProps and display them within the same component?

What is the proper way to map a list of images returned using getStaticProps? I had successfully implemented this by passing a prop to the gallery component in another page. However, I now want to consolidate all the getStaticProps code within the gallery ...

Incorporating a newline character into a React state string

I am currently developing a next JS application and utilizing react states within it. My goal is to incorporate a line break in a string value of the state. I have experimented with several methods like the ones below, but none seem to be effective: setS ...

I'm unable to import correctly using the --compiler option

Having an issue here. I'm trying to bring in the typescript compiler. I used this command: bit import bit.envs/compilers/typescript --compiler Unfortunately, it didn't work. This is the error message: bit import [ids...] import components in ...

Drag and drop feature malfunctioning - items cling to one another and rearrangement is imprecise

For my current project, I am utilizing react-beautiful-dnd, Chakra UI, and Next.js. If you're interested in seeing the issue in action, check out this video: https://youtu.be/8maSmqahjfw. Despite attempting various methods like ondragupdate, ondragsta ...

Changing the State of a CheckBox with ReactJS and Material UI

Utilizing Material UI's Checkbox, I am creating a form to input data and update or add values into a state object. This form serves the purpose of both editing an existing holiday or adding a new one. I'm currently facing an issue where the stat ...

Issue encountered while establishing a connection between my React application and the Heroku server

I'm having trouble resolving an error that occurs when trying to connect my front-end React App with my Heroku server App. Whenever I send a request from the front-end, I encounter the following issue: Failed to load : No 'Access-Control-Allow ...

Changing the className of buttons based on user interaction

I'm looking to create a function in React JS that changes the button's color when clicked. Specifically, I want the color of the button to change upon clicking. I have attempted to achieve this using the following code: {"classname" i ...

Setting up an empty array as a field in Prisma initially will not function as intended

In my current project using React Typescript Next and prisma, I encountered an issue while trying to create a user with an initially empty array for the playlists field. Even though there were no errors shown, upon refreshing the database (mongodb), the pl ...

I recently upgraded to Next v13 and I've been grappling with integrating redux. However, I keep encountering a context error. Can someone please advise me on what I might be doing incorrectly and suggest possible solutions?

I am embarking on creating a new game and need to maintain track of the user's life within the redux store. To accomplish this, I crafted a life slice as shown below: export const lifeslice = createSlice({ name: "life", initialState: { ...

How can the parent state be updated in ReactJS when the child state changes?

I am facing an issue with a component called AppBarRight. When a button is clicked, a backend function should be called and then its parent component, AppBar, should render another component called MyList. However, the provided code is not working as expec ...

Mui Select fails to update value when defaultValue is specified

I am using a select component from the MUI React library along with react-hook-form and controller. I have set a default value in the controller to use the reset function, but I am unable to change the value when a default value is set. Everything works ...

Is there a way to dynamically set the value of a React Material TextField in Auto Select mode?

Here is a React state: const [filterByInvoiceNo, setFilterByInvoiceNo] = useState( 0 ); This represents a React Material TextField: <TextField size="small" type="number" label="Invoice No&quo ...

Validating React Typescript Props: Ensuring that two specific props do not exist simultaneously

Currently, I'm developing a reusable component in React-Typescript and I am looking to validate my props OnClick and component as follows: Both onClick and component prop are optional. These props will only be passed to the component if they need to ...

Ensuring the Persistence of Column State in Material-UI DataGrid/DataGridPro when Adjusting Visibility Using Column Toolbar

We have integrated MUI DataGrid into our React project. Currently, I am exploring options to save the state of columns after toggling their visibility using the DataGrid toolbar column menu. After each re-render, the column setup returns to its default st ...

How can I adjust the font size in a TextField when it is in focus?

As a novice in ReactJS, I am currently utilizing materia-ui to design a page. I am looking to make a custom change on a TextField where the font size adjusts when text is entered. However, adjusting the font size creates too much space between the label a ...

muiSlider limited to specific range

I am currently using the Mui Slider component for a user interface where I need to restrict its value within a certain range. For example, I want the slider's handle to become unmovable after reaching 50. Users can still select values up to 50, but th ...

Unable to rectify the installed npm module issue

I removed the @toast-ui/react-image-editor package from my react app's server side thinking it needed to be on the client side. After installing it on the client side and restarting the app, it could not be found. Here is a basic overview of my folde ...

Prevent the browser from autofilling password information in a React Material UI textfield when it is in focus

I am currently utilizing React Material UI 4 and I am looking to disable the browser autofill/auto complete suggestion when focusing on my password field generated from `TextField`. Although it works for username and email, I am encountering issues with d ...