Can a props be retrieved and passed as an argument to a function?

My goal is to retrieve a prop from MapsStateToProps using react-redux's connect and then pass it to a child component. This prop serves as an argument for a function, which in turn returns something that becomes the state of the child component.

Although I can see that the props are being updated, the change doesn't reflect immediately when used as an argument. Instead, I have to navigate to another component (using react-routers) and then return to the original component to see the desired result. Is there a way to make this change happen without having to switch components? Perhaps I'm missing something, or maybe what I'm attempting isn't the ideal method in React. Any advice?

import React, { Component } from 'react';
import {connect} from "react-redux";
import filterData from "../../States/AllStates/filterData"
import BookComponent from "./BookComponent";

const mapStateToProps = state => { 
    return {
    fmlProps: state.ReducerName.fmlProps
    }
};

class Testing extends Component {
    state = {
        // The use of this.props.fmlProps does not update immediately. Requires switching components
        XXX: filterData(this.props.fmlProps)
    }
    
    render() { 
        return (
            <>

            <h1>{this.props.fmlProps}</h1> {/* correct value displayed */}

            {this.state.XXX.map(FakeData => (
                <BookComponent
                    key={FakeData.planNumber}
                    PNum={FakeData.planNumber}
                    PName={FakeData.planName}
                />))}

            </>
        );
    }
}

export default connect(mapStateToProps, null)(Testing);

Answer №1

Utilize the componentDidUpdate method to monitor and trigger a function when the component has finished updating.

componentDidUpdate(prevProps) {
  // Typical usage (remember to compare props):
  if (this.props.fmlProps !== prevProps.fmlProps) {
    //invoke function and update state
    const newData = filterData(this.props.fmlProps);
    this.setState({newData});
  }
}

For more information, check out - https://reactjs.org/docs/react-component.html#componentdidupdate

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

Map Loader for GeoJson Leaflet Integration

Although my English skills are not perfect, I will do my best to explain my issue. I have some knowledge of javascript / html / ajax and I have created a webgis using Leaflet. The problem arises when loading a large geojson file onto the map - it takes qui ...

Using jQuery to add a class to an input option if its value exists in an array

Looking for a way to dynamically add a class to select option values by comparing them with an array received from an ajax call. HTML <select id="my_id"> <option value="1">1</option> <option value="2">2</option> ...

Implementing a configuration file into a client-side web application using asynchronous methods

Currently, I am facing a challenge with an SPA that is being developed using various custom components from different sources. The main issue at hand is how to initialize certain settings (such as Endpoint URLs) using a settings file that can be configure ...

Vue Testing Utilities - issue with data not updating upon click event activation

I recently created a basic test using Vue Test Utils: import { mount } from '@vue/test-utils' const App = { template: ` <p>Count: {{ count }}</p> <button @click="handleClick">Increment</button> `, ...

Negative vibes with for/in loop

My script is short and simple: hideElements = arguments.shift().split(','); for (iterator in hideElements) { console.log('--> hiding ' + hideElements[iterator]); lg_transitions({kind:"slide-up"}, {target: hideElements[iterat ...

Experiencing a problem with Datatables where all columns are being grouped together in a single row

After creating a table with one row using colspan and adding my data to the next row, I encountered an issue with the datatables library. An error message appeared in the console: Uncaught TypeError: Cannot set property '_DT_CellIndex' of unde ...

"Browser compatibility issues: 404 error on post request in Firefox, while request is

When following this tutorial on React and PostgreSQL, the app should display the JSON fetch in the bash terminal around the 37-minute mark. However, there seems to be a problem as there is no feedback showing up on the npm or nodemon servers. After tryin ...

The notify.js fails to display notifications in the event of an error

Why am I not receiving any error notifications even when there is an error message in the response object? $.ajax(settings).done(function (response) { if ( "error_message" in response ) { console.log(response); $.notify(" ...

Retrieve an item from a MongoDB database using Mongoose

It seems like a simple problem, but my brain is struggling to comprehend the issue at 2 AM. I'm working on creating a profile page that displays basic public information. My approach involves retrieving the user's username from MongoDB based on t ...

Can the JavaScript code be altered within the client's browser?

So, I'm using JQuery Validator on my webform to validate form data. However, I haven't added any validation on the server side. I'm curious if it's possible for a user to modify the code and bypass my validations in their browser. If th ...

Tips for Showing Certain Slides When the Page Loads

When using jQuery filter effects to organize div slides on a page, I encountered an issue where all the divs containing different slides are displayed on page load instead of just the default chosen ['active'] div. The filter effect itself is fun ...

Angular: Issue with click() event not functioning properly once dynamic HTML is rendered

There are a few HTML elements being loaded from the server side, and an Angular click() event is also included. However, the event is not firing after the elements are rendered. It is understood that the DOM needs to be notified, but this cannot be done. ...

What is causing this code to not produce the expected result of 8.675?

Recently, I encountered a challenge on freecodecamp I managed to write the code successfully, but unfortunately, my browser crashed and I lost all the progress. When I attempted to rewrite the code, it was returning an incorrect answer (a value of 2). I& ...

dispatch a WebSocket message within a route using Express.js

The Objective: Imagine a bustling marketplace with multiple shops. I'm working on a dedicated page localhost:3000/livePurchases/:storeId for shop owners to receive real-time notifications whenever they make a new sale. https://i.stack.imgur.com/VdNz ...

Encountering issues with accessing image files located in the public folder of my Next.js project - Receiving a 404 Error message

I am currently facing an issue with my Next.js project where I am unable to use image files from the public folder. Despite checking that the file paths, names, and extensions are correct, as well as ensuring my configurations are accurate, I keep encounte ...

How to horizontally align Material-UI elements in ReactJS

My goal is to create a user-friendly form where respondents can input answers to questions and select one as the preferred option by using a radio button. However, I'm facing an issue where Material-UI displays each element on its own line. This is t ...

Utilizing ng-style with a ForEach loop on an Object

How can I dynamically add a new style property to objects in an array in Angular, and then use that property inside ng-style? CommentService.GetComments(12535372).then(function () { $scope.comments = CommentService.data(); angular.forEac ...

Unlocking the WiFi Security Key and Accessing Connected Devices with Javascript

When utilizing the command line netsh wlan show interfaces, it displays various information. However, I am specifically interested in extracting the data Profile : 3MobileWiFi-3D71. My goal is to retrieve only the content after the : so that ...

Modifying iframe src using click event from a separate component in Angular 10

I am looking to dynamically update the src attribute of an iframe when the menu bar is clicked. The menu bar resides in a separate component and includes a dropdown menu for changing languages. Depending on which language is selected, I want to update the ...

Getting React Developer Tools to Function with Webpack

I recently followed a tutorial on how to expose React as a global variable in Webpack using the Expose module. Despite installing the Expose module and adding the appropriate loader configuration in the webpack.config.js file, I am still unable to access R ...