DEV Community

loading...

React state not updating properly

PDavor
・2 min read

Hello everyone, I'm begginer at React and got stuck on updating state.

State is array of objects, on click of radio button data is sent to state.

I want if user presses another button from same group, to just update object in array, instead of making new one.

So far object updates, but not if user clicked on other radio group, then it creates new object, desipte id beign same.

Here is full code, homefuly someone can see what is wrong with code, thanks!

import { React, useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import "./Provjera.css";
const Provjera = () => {
  let { id } = useParams();
  const [data, setData] = useState();
  const [isLoading, setIsloading] = useState(true);
  const [rjesenje, setRjesenje] = useState([]);
  const handleRjesenje = (event) => {
    rjesenje.length > 0
      ? rjesenje.map((item, index) => {
          if (item.pitanje_id === event.target.name) {
            let temp = [...rjesenje];
            temp[index] = {
              pitanje_id: event.target.name,
              odgovor: "there was same id",
            };
            setRjesenje(temp);
          } else {
            setRjesenje([
              ...rjesenje,
              {
                pitanje_id: event.target.name,
                odgovor: "there wasnt same id",
              },
            ]);
          }
        })
      : setRjesenje([
          ...rjesenje,
          { pitanje_id: event.target.name, odgovor: "array was empty" },
        ]);
  };
  useEffect(async () => {
    axios
      .get(`http://localhost:5000/kategorije/provjere/${id}`)
      .then((res) => {
        //let provjera = res.data;
        setData(res.data);
        setIsloading(false);
        //console.log("provjera", data[0].provjere);
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);
  return (
    <div>
      <div>
        {!isLoading &&
          data[0].provjere
            .filter((p) => p._id.includes(id))
            .map((nez) => <h1>{nez.naziv}</h1>)}
      </div>
      <div>
        {!isLoading &&
          data[0].pitanja.map((p) => (
            <fieldset id={p._id} className="field" disabled={false}>
              <h4>{p.pitanje}</h4>
              {p.odgovori.map((o) => (
                <div>
                  <input
                    type="radio"
                    value={o}
                    key={o}
                    name={p._id}
                    onClick={handleRjesenje}
                  />
                  <label for={o}>{o}</label>
                </div>
              ))}
            </fieldset>
          ))}
      </div>
    </div>
  );
};

export default Provjera;

Enter fullscreen mode Exit fullscreen mode

Discussion (0)