Map failing to refresh

Having some trouble with the map function as it's not updating my select box with the new selected value. The issue occurs within a material UI dialog that appears when viewing a file. I notice that the values get updated only after closing and reopening the modal, but they don't refresh otherwise. Any assistance on this matter would be highly appreciated.

import React, { useEffect, useState } from 'react';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import InputLabel from '@material-ui/core/InputLabel';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
import { makeStyles } from '@material-ui/core/styles';
import MenuItem from '@material-ui/core/MenuItem';

import filter from '../../../constants/filter-options';
 
export default function KeywordFilter(props) {
    
    const [selectedFilter, setFilter] = useState(props.selectedFilter);
    
    const [filterOptions, setFilterOptions] = useState(filter);

    const useStyles = makeStyles(theme => ({
        root: {
            flexGrow: 1
        },
        paper: {
            padding: theme.spacing(2),
            textAlign: 'center',
            color: theme.palette.text.primary,
        },
        modal: {
            height: '80vh',
            width: '40vw',
            maxWidth: '40vw'
        }
    }));

    const classes = useStyles();

    const handleChange = (event, keyword) => {
        var temp =  selectedFilter;
        
        temp[keyword] = event.target.value;
        console.log("TEMP: ", temp)
        console.log("keywordList: ", keywordList)

        props.onFilterChange(temp);
        setFilter(temp)
        setFilterOptions(filter)
    };

    const keywordList = Object.keys(filterOptions)

    
    return (


        <div key={keywordList}>
            <h4 style={{textAlign:'center'}}>Filters: </h4>
            <Grid container spacing={3}>
                {keywordList.map((keyword) => {
                    return (
                        <Grid item xs={6}>
                            {console.log("selectedFilter: ", selectedFilter)}
                            <Paper className={classes.paper}>
                            {keyword}:&nbsp;<FormControl className={classes.formControl}>
                                                <Select
                                                    key={keyword}
                                                    labelId="demo-simple-select-label"
                                                    id="demo-simple-select"
                                                    value={selectedFilter[keyword] ? selectedFilter[keyword] : "None"}
                                                    onChange={(e) => handleChange(e, keyword)}
                                                >
                                                    {filterOptions[keyword].map(element => <MenuItem value={element}>{element}</MenuItem>)}
                                                </Select>
                                            </FormControl>
                            </Paper>
                        </Grid>
                    )}
                )}
            </Grid>
        </div>
    ); 
}

The filter module resembles the structure below:

const filter = 
{
    Schedule : ["None", "Monthly", "Quarterly", "Semi-Annually",  "Annually"],    
    Chemical : ["None", "Copper", "Phosphorus"],
    Color : ["None", "Black", "Blue"]
}

export default filter;

Answer №1

After some troubleshooting, I discovered that directly modifying the state was causing a multitude of issues. By making some adjustments to the handleChange function and eliminating unnecessary code, I was able to resolve the issue:

import React, { useEffect, useState } from 'react';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
import { makeStyles } from '@material-ui/core/styles';
import MenuItem from '@material-ui/core/MenuItem';

import filter from '../../../constants/filter-options';
 
export default function KeywordFilter(props) {

    const useStyles = makeStyles(theme => ({
        root: {
            flexGrow: 1
        },
        paper: {
            padding: theme.spacing(2),
            textAlign: 'center',
            color: theme.palette.text.primary,
        },
        modal: {
            height: '80vh',
            width: '40vw',
            maxWidth: '40vw'
        }
    }));

    const classes = useStyles();

    const handleChange = (event, keyword) => {
        
        // Make a deep copy of selected filters to prevent direct state modification
        const target = JSON.parse(JSON.stringify(props.selectedFilter)) 
        // Set new value to add
        const source = { [keyword]: event.target.value};
        // Merge the two objects (this also updates the target)
        const results = Object.assign(target, source)
        // Update the state
        props.onFilterChange(results)
    };

    return (
        <>
            <h4 style={{textAlign:'center'}}>Filters: </h4>
            <Grid container spacing={3}>
                {Object.keys(filter).map((keyword) => {
                    return (
                        <Grid item xs={6}>
                            <Paper className={classes.paper}>
                            {keyword}:&nbsp;<FormControl className={classes.formControl}>
                                                <Select
                                                    key={keyword}
                                                    labelId="demo-simple-select-label"
                                                    id="demo-simple-select"
                                                    value={props.selectedFilter[keyword] ? props.selectedFilter[keyword] : "None"}
                                                    onChange={(e) => handleChange(e, keyword)}
                                                >
                                                    {filter[keyword].map(element => <MenuItem value={element}>{element}</MenuItem>)}
                                                </Select>
                                            </FormControl>
                            </Paper>
                        </Grid>
                    )}
                )}
            </Grid>
        </>
    ); 
}

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

Troubleshooting tips for optimizing Opera and Internet Explorer performance

I'm currently on the hunt for solutions or techniques to debug my jquery script specifically under the Opera/IE browser. It appears that the ajax $.post() request is either not being sent at all, or it's being sent to the wrong address, among oth ...

JavaScript Function to Retrieve URL Parameter in PHPIn this tutorial

I'm currently working on an HTML5 game where each level has its own dedicated HTML page. The results of each level are saved in a JavaScript variable. My question is, how can I pass this information to the next page using the URL? I was considering ...

I encountered a RangeError with code [ERR_HTTP_INVALID_STATUS_CODE] due to an invalid status code being undefined

I have encountered a specific error while running my note-taking app. The error seems to be related to the following piece of code - app.use((err,req,res,next)=>{ res.status(err.status).json({ error : { message : err.message ...

Obtaining the correct information from an array using Ionic's Angular framework

I am currently working with an array of data that contains arrays within each item. I have been able to display the data as needed, except for the IDs. Approach Show arrays within the array Retrieve the IDs of the arrays (excluding the IDs inside the ar ...

What is the method to access and examine the attributes of a range in Office.js?

I am encountering an issue while attempting to retrieve the values from cell B2 and create a conditional statement based on those values. Despite my efforts, I continue to receive an error message without any clear understanding of its cause. Please refe ...

JavaScript Transformation of Date Format

var dt="29/05/2013"; //DD/MM/YYYY I am looking to change the format to yyyy/MM/dd; My current approach is: var newdate=dt.getFullYear()+"/"+dt.getMonth()+"/"+dt.getDate(); Is there a more straightforward way to convert it without using substring? No p ...

Is there a way to simultaneously modify several data variables within a Chart.js label?

I'm currently working on dynamically updating a line chart with two data entry points using the variable name "data." Take a look at the code snippet below: var lion = new Chart(ctx2, { type: "line", data: { labels: ["Apr", "May", ...

Creating a versatile JavaScript library that is compatible with various platforms such as browsers, NodeJS, and single page applications like React

My question is: Is it possible to convert a basic file into a versatile library that can be utilized with Browsers (via script tag), Node JS, and Single Page Applications using a single codebase? In the past, I have primarily used existing libraries witho ...

Transmit information using JSON format in Angular 8 using FormData

i am struggling with sending data to the server in a specific format: { "name":"kianoush", "userName":"kia9372", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcd7d5ddd8ce85...@example.com</a>" } H ...

Should all pages in React be rendered on the server side?

Currently, I rely on Next.js for implementing server-side rendering on my React website. At the moment, I have implemented server-side rendering across almost all pages of the site, including profile information and other content that requires a login to ...

Utilize JavaScript and jQuery to extract the selected text's context from a webpage

I'm looking to extract the contextual information surrounding a selected text on a web page, specifically the 25 words before and after it. I've tried using JavaScript and jQuery with the following code snippet but unfortunately, it doesn't ...

Booking.com's embedded content is experiencing display issues

My current project involves adding a booking.com embedded widget. Initially, when accessing the main page, everything works perfectly - the map and booking widget are visible for ordering. However, if you switch views without leaving the page or closing th ...

Adding custom script tags to a React application

I'm interested in integrating a StreamingVideoProvider video player into my React application but facing some challenges: I do not have direct access to the video URL I want to utilize their JS video player for its advanced features like password pro ...

Calculate the sum in real-time using JavaScript

How can I dynamically compute the sum of subtotals without encountering the following error? document.getElementById("item_subtotal[" + cnt + "]") is null Below is my JavaScript code: function calculateTotalAll(numitems) { var cnt = 1; var tot ...

Should I use a separate webpack configuration for server-side rendering in React npm package?

I am the developer of a small npm package and I am currently facing challenges while trying to implement it in a Gatsby site. Despite my efforts, I am struggling to ensure that my npm package is ssr safe due to my limited knowledge of webpack. When attemp ...

Having trouble getting $compile to work in an injected cshtml file with Angular

Summary I am currently working on a large application where everything is designed to be very generic for easy expansion. One of the components I am focusing on is the dialog. Before suggesting alternatives like using ngInclude or angular templates, let m ...

Issue encountered with search.run().getRange function when accessing a stored search in suitescript 2.0

I am facing an issue with my saved search in the beforeLoad userevent script. After adding a filter and running the search, Netsuite throws an UNEXPECTED_ERROR. Any ideas on what might be causing this error? var poRec = context.newRecord; var countIt ...

Performing a $.POST request on a Squarespace webpage

I created a custom form on my website for booking appointments, and it posts to a third-party server. When I submit the form using the <form> tag, I receive the email notification. However, I want to submit the form using $.POST so that I can customi ...

Limiting the zoom in three.js to prevent object distortion caused by the camera

I'm currently in the process of developing a three.js application where I have successfully loaded my STL objects and incorporated 'OrbitControls'. However, I am encountering an issue when attempting to zoom using the middle scroll button on ...

Stop geocomplete from providing a street address based on latitude and longitude coordinates

Is there a way to prevent geocomplete from displaying the street portion of the address when passing lat and lng coordinates? Here's an example: If I pass these coordinates to geocomplete: var lat = '40.7127744' var lng = '-74.006059& ...