graysonmcm
graysonmcm

Reputation: 87

How to add to state or otherwise replace state if key exists?

I have a few radio buttons and I would like to generate dynamic state by setting the state with the first initial click, then every click after either concatenating the state onto the current state or replacing the key with a new value if it already exists.

I have attempted it by myself, so excuse myself if it doesn't look right at all.

Here is a sample of what I am trying to do.

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
            // checked={parentCheckedGood}
            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
            // checked={parentCheckedNA}
            name={Question}
            type="radio"
            id={string + "4"}
            value="N/A"
            label="N/A"
          />
        </div>
      </FormGroup>
    </div>
  );
}

export default Ratings;

These radio buttons are giving me a run for my money.. Cheers

Upvotes: 1

Views: 917

Answers (1)

Ross Allen
Ross Allen

Reputation: 44880

Use the function format of setState, and you were close on the syntax:

const handleChange = (e) => {
    const { name, value } = e.target;
    setState(state => ({ ...state, [name]: value }))
};

Upvotes: 2

Related Questions