Invoke a function on React whenever the context is updated

Within my functional component, I have a scenario where it returns another function:

function Lobby() {

const user_context = useContext(UserContext)

   return (
        <div>{renderData(user_context.state.data)}</div>
   )
}

export default Lobby;

The problem arises when there is a change in the user_context, the Lobby() function does not update, causing renderData() to remain stagnant. How can I ensure these functions are called upon a change in the user_context?

(UPDATE) Here are more specifics:

    <App />
      <UserContext />
        <Lobby />
          <Introduction />
          <Chapter_1 />
          <Chapter_2 />
          <Chapter_3 />

The UserContext includes a method called finishChapter, which is invoked by a user click within the Introduction. This triggers an update of the chapter in the state of the context and passes the new chapter to the Lobby.

UserContext.js

import React, { createContext, Component } from 'react';
import axios from 'axios';

export const UserContext = createContext();

class UserContextProvider extends Component {

    constructor(props){
        super(props)
        this.state = {
        }
    };

    toggleLoading = () => {
        this.setState({loading: !this.state.loading})
        setTimeout(() => {this.setState({loading: !this.state.loading})}, 1000)
    }

    finishChapter = (chapter) => {
        axios.put(`/narrative/finish_chapter/${chapter}`).then((done)=> {
            this.toggleLoading()
            this.getChapter()
        })
    }

    getChapter = () => {
        axios.get('/narrative/get_narrative').then(result => {
            this.setState({
                chapters_complete: result.data[0].chapters_complete,
                number_ch_complete: result.data[0].chapters_complete.length
            })
        })
    }   

    render() {
        return (
            <UserContext.Provider value={{state: this.state, toggleLoading: this.toggleLoading, finishChapter: this.finishChapter }}>
            {this.props.children}
            </UserContext.Provider>
        )
    }

}

export default UserContextProvider;

Once the new chapter is reflected in the context, I intend for Lobby to close Introduction and open Chapter_1.

Presently, although Lobby receives the updated context (e.g., 'Chapter_1' as seen in Chrome tools), it fails to execute the required function.

Answer №1

Appreciation for the valuable feedback, and a shoutout to @Cully for shedding light on how re-renders and UserContext operate.

Ultimately, it boiled down to a flaw in the data structure.

Incorrect:

renderData(user_context.state.data)

Correct:

renderData(user_context.state.data.chapters_complete)

An admittedly silly error, but the supportive input guided me to the right solution. Gratitude to the wonderful SO community.

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

Improved Node.js algorithm designed to identify anagrams of a specific string in an array. The approach must not rely on generating all possible subsets to find the anagram of the string

I am looking to create a collection of anagram pairs within an array. The input will consist of the initial array of strings. For example: let inputArray = ["abcd", "dbac", "adfs", "adsf", "bDca"]; This program should consider the case of the letters, m ...

Encountering the error message "TypeError: setValue is not a function" while trying to pass it as a

Struggling to update the useState() variables by receiving input from a child component nested within another child component. However, encountering an error message when attempting to call either setItem() or setValue() functions from the useState() decla ...

Switch between classes when hovering over / exiting ngFor elements

Displayed below is an element created using ngFor <span *ngFor="let picture of pictures; let i = index"> <a target="_blank" href="{{picture.image}}" class="thumbnail-display image-overlay"> <span class="overlay-icon hide"> ...

Issue with clientHeight not functioning properly with line breaks in Angular 2 application after ngAfterViewInit

I have successfully created a Gridify page in my Angular 2 application using the Gridify library. To initialize it, I've utilized a custom ngAfterViewChecked method: ngAfterViewChecked() { var selector = document.querySelector('.read-grid& ...

What is the best way to display a Nested JSON structure without an object key?

Need help with extracting data from two different JSON structures. The first one is straightforward, but the second is nested in multiple arrays. How can I access the content? See below for the code snippets: // First JSON { "allSuSa": [ { ...

Steps for appending a string to a variable

Currently working on creating a price configurator for a new lighting system within homes using Angular 7. Instead of using TypeScript and sass, I'm coding it in plain JavaScript. Page 1: The user will choose between a new building or an existing one ...

Utilizing pure JavaScript to dynamically fetch HTML and JavaScript content via AJAX, unfortunately, results in the JavaScript

I am trying to load an HTML file using AJAX and then execute a script. Here is the content of the HTML file I want to load: <div class="panel panel-body"> <h4>Personal Data</h4> <hr /> <span data-bind="editable: firs ...

Is there a method to consistently keep the horizontal scrollbar in view for the MUI Data Grid at all times?

I have a Data table with virtualized columns, totaling more than 25 in number. Users can easily scroll horizontally using a trackpad, but without one, they may struggle to access all the columns due to the delayed appearance of the scrollbar. Is there a w ...

Submitting a form using jquery

I am working on a project that involves using a jquery fancyzoom box. Within this box, there is a contact form that should send an email upon submission. However, I am encountering issues with calling the form submit function due to the fancyzoom feature. ...

Tips for postponing the execution of inline javascript

Main page <script> $.ajax({ type: 'GET', url: 'ajax.php', context: document.body, success: function(data) { $("#content").html(data); } }); </script> <div id="content"></div> Ajax ...

Why is my custom 404 page failing to load after building my Next.js application?

I recently set up a custom 404 page for my Next.js app and wanted to test it locally before deploying to the server. To do this, I used the "serve" package to host the project on my local machine. However, when I tried navigating to a non-existent page, th ...

Is there a way to execute a code snippet just once when focusing on a specific field?

<form id="myForm"> <label for="fname">First name:</label><br> <input type="text" id="fname" name="fname"><br> <label for="mname">Middle name:</label> ...

What is the best way to establish a connection between the same port on Expressjs and Socket.io

I am currently using Express.js and Socket.io to develop a chat application. Initially, I created my project with Express-Generator and began by running the node ./bin/www script. However, I decided to remove the ./bin/www file and instead combined it wit ...

What could be hindering the activation of my button click event?

Below is the js file I am currently working with: var ButtonMaximizer = { setup: function () { $(this).click(function(){ console.log("The maximize button was clicked!"); }); } }; $(docum ...

Utilizing dynamic URLs to transfer query parameters between pages

I need to include an additional parameter when navigating to a different page. I attempted the following with ?extraParam=[data.buildingName] but it is not functioning as expected. <Link href="/accounts/[accountId]/buildings/[buildingId]/gateways/[ga ...

Browserify is unable to locate the 'jquery' module

While attempting to package my app with browserify, I encountered the following error message: Cannot find module 'jquery' from '/home/test/node_modules/backbone' I have searched for solutions to this issue, but none of them seem to ...

How can one ensure that Discord waits for a script to complete running, and how can you prevent Discord from responding until all necessary data has been obtained?

I recently started working with node.js and asynchronous programming, and I'm facing a challenge that has me puzzled. My goal is to create a Discord bot that fetches data from a third-party website. While I can successfully retrieve the data and see i ...

Exploring ways to access elements within shadow-root (open) in Angular using SVG.js

I'm currently tackling a project involving Angular Elements. Within this specialized component, my goal is to incorporate SVG.js 3+. However, due to the necessity of utilizing ViewEncapsulation.ShadowDom in my component, I am encountering challenges w ...

Exploring arrays and objects in handlebars: A closer look at iteration

Database Schema Setup var ItemSchema = mongoose.Schema({ username: { type: String, index: true }, path: { type: String }, originalname: { type: String } }); var Item = module.exports = mongoose.model('Item',ItemSchema, 'itemi ...

What methods can be used to test included content in Angular?

When testing an Angular component that includes transclusion slots utilizing <ng-content>, it becomes challenging to verify if the transcluded content is correctly placed within the component. For instance: // base-button.component.ts @Component({ ...