What is the best way to update the state by either adding to it or replacing it if the key

I'm currently working on a project involving radio buttons and I need to create dynamic state by setting the initial state on the first click, then updating it with subsequent clicks by either concatenating the new value onto the existing state or replacing it if the key already exists.

I've given it a shot on my own, so please bear with me if it's not quite right.

Below is a snippet of what I'm trying to achieve:

import React, { useState } from "react";
import { FormGroup, CustomInput } from "reactstrap";
import UniqueString from "unique-string";

function Ratings({ parentCheckedGood, parentCheckedNA, Question }) {
  //initializing empty state object
  const [state, setState] = useState({});
  //Here is where I am stuck, with each click after the first I should concatenate or 
  //replace
  const handleChange = (e) => {
    const { name, value } = e.target;
    if (name in state) {
      setState(...state, { name: value });
    } else {
      setState(...state, {
        name: value,
      });
    }
  };
  console.log(state);
  const string = UniqueString();
  return (
    <div>
      <FormGroup required>
        <div onChange={handleChange}>
          <CustomInput
            type="radio"
            id={string + "1"}
            name={Question}
            value="Good"
            label="Good"
          />
          <CustomInput
            type="radio"
            id={string + "2"}
            name={Question}
            value="Fair"
            label="Fair"
          />
          <CustomInput
            type="radio"
            id={string + "3"}
            name={Question}
            value="Poor"
            label="Poor"
          />
          <CustomInput
            name={Question}
            type="radio"
            id={string + "4"}
            value="N/A"
            label="N/A"
          />
        </div>
      </FormGroup>
    </div>
  );
}

export default Ratings;

Figuring out these radio buttons is proving to be quite a challenge, but I'm determined to crack it. Here's to perseverance!

Answer №1

To correctly update the state in React using the setState function, you can follow this syntax:

const handleInput = (e) => {
    const { id, val } = e.target;
    setState(prevState => ({ ...prevState, [id]: val }))
};

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

When the Protractor configuration is executed, it displays the message "The requested webpage cannot be accessed."

Testing protractor on a vanilla.js app and encountering an error when running protractor basicConf.js The following error is occurring: This webpage is not available ERR_CONNECTION_REFUSED Here is the test script in use: describe('foo', fun ...

"Integrating multiple partials with templateUrl in AngularJS: A step-by-step

Is there a way to merge partial views using the templateUrl attribute in an AngularJS directive? Imagine having a directive like this: .directive('combinePartials', function () { var mainPartial = "mainpartial.html", var template2 = "pa ...

Encountered error code 3228369023 while trying to establish a connection to a SQL Server database using Node.js with MSSQL

Currently in the process of setting up an API for a SQL Server Express database, my plan is to utilize mssql in Node.js with express to handle requests and communicate with the database. Despite trying several methods to establish a connection between my n ...

Setting up Webpack and Babel for ReactJS development

Recently, I started delving into the world of ReactJS and stumbled upon a tool called webpack which acts as a module bundler. However, I've hit a roadblock while configuring it and keep encountering the following error message: ERROR in ./src/index. ...

The React Native Expo is throwing an error stating that it is unable to locate the module 'minizlib'

At the instructions available in the read.me of https://github.com/react-community/create-react-native-app Upon selecting my template using the expo init command, I encountered the following error: Cannot find module 'minizlib' Error: Cannot fi ...

Creating HTML elements with dynamic `routerLink` attributes in Angular 2

I have a model that references itself, as shown below. export class Entity { constructor(public id: number,public name: string,public children: Entity[]) { } } My goal is to create a tree list where each item has a routerlink. To achieve this, I ...

After updating the data, the React Material UI Grid Item fails to render

I am encountering an issue where the code fails to render grid items when there is a change in props.data from the top component. import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Grid from '@ ...

Utilizing numerous Rails API POST requests has become a common practice

Currently, my ReactJS application is connected to a Rails 5 API. The React application sends a single JSON POST request to api/v1/job in order to create a new job record. This request contains information for two HABTM relationships with Tools and Technol ...

Strategies for extracting targeted information from my mondoDB records

I am seeking guidance on selecting specific data to transmit to my state, as currently it is sending all information when I only require 'firstname', 'lastname', email, and so forth. Below is the NodeJS code snippet for my backend call ...

Using the Table-multiple-sort feature in boostrap-table is not functioning properly when there are multiple tables present on a single page

I have implemented bootstrap-table along with the extension table-multiple-sort. The issue I am facing is when I include two tables on a single page (with the second table within a modal window), the multisort feature does not seem to work on the second ta ...

Unable to locate module with React and Material-UI integration

When attempting to implement a Material button in my React app, I encountered the following error: Failed to compile. ./node_modules/@material-ui/core/styles/index.js Module not found: Can't resolve '/Users/hugovillalobos/Documents/Code/Lumiere ...

Developing modular applications with Vue.js and leveraging locally installed NPM packages

I am currently working on developing a modular application using Vue through the vue-cli-service. The main application and its modules are located in separate folders, with a structure that looks something like this: -- app/package.json /src/** -- mo ...

Exploring the benefits of integrating Apache Thrift with TypeScript

After running the apache thrift compiler, I now have generated .js and .d.ts files. How do I incorporate these files into my current Angular2/Typescript project? I attempted to do so with the following lines of code: ///<reference path="./thrift.d.ts"/ ...

Exploring the Power of Elasticsearch with Datatables

I'm attempting to utilize functions from an Elasticsearch instance in conjunction with datatables to exhibit results. Currently, I am only able to display 10 results, regardless of the query used. Even though there are 141,000 results in Elasticsearc ...

Setting radio button value while redirecting to a new page using Next.js

I'm in the process of developing a quiz application using Next.js. Within my app, I have implemented two buttons - one for navigating to the next question and another for going back to the previous question. When selecting an answer for a question usi ...

The $.post method is malfunctioning

I am experiencing an issue where the onchange function is working properly, but the $.post function is not functioning as expected. Below is the HTML code snippet: <input type="checkbox" id="chk" value="3" onchange="checkradio(this.value)"/> Here ...

Make sure to include the onBlur and sx props when passing them through the slotsProp of the MUI DatePicker

This DatePicker component is using MUI DatePicker v6. /* eslint-disable no-unused-vars */ // @ts-nocheck import * as React from 'react'; import { Controller } from 'react-hook-form'; import TextField from '@mui/material/TextField&a ...

Discover the best way to utilize useEffect on the server within Next.JS 14!

How can I effectively implement the useEffect functionality in Next.JS server components? I attempted to use useEffect on the server side but it was unsuccessful. Are there alternative hooks that can be utilized on the server side? If not, what is the bes ...

When a function is called, retrieve a specific number of elements from an array using the slice method in

If I have an array of 15 objects, but I am only displaying 5 on the browser using this code: const displayedArray = array.slice(0,4) I also have a function that will load another 5 objects each time a user scrolls down. displayedArray.concat(array.slice ...

What is the process for removing a registered user from Realm Object Server with the use of the Javascript library?

I have been searching online for a solution, but I haven't been able to find an answer. I am attempting to remove a user from ROS, however, I cannot locate a designated API for this task. The version of my realm-js is 1.10.3. If this feature does not ...