2

Tengo una api para encuestas, las respuestas son opcionales y libres. Guardo en un array las respuestas libres, y en otro las opcionales y despues las uno.

Pero el problema es que si el usuario cambia de respuesta se va a seguir guardando en el array duplicando la pregunta.

Lo que necesito es que al guardar la respuesta en el array compare si ya existe ese id de pregunta y borre el anterior y añada el nuevo.

He intendado algo asi pero me borra la respuesta nueva, no la anterior: Ejemplo, idPregunta es 28 en ambos pero debe eliminar el primero que encuentre, osea el object 1, aunque idRelacion sea diferente:

1: Object
idRelacion: 1212
idPregunta: 28

2: Object
idRelacion: 1111
idPregunta: 28

demo

import React, { useState } from "react";
import ReactDOM from "react-dom";

export default function App() {
  var respuestas = [];

  const preguntas = [
    {
      idEncuesta: 7,
      encuesta: "Encuesta2 ",
      idPregunta: 26,
      pregunta: "¿Que tan probable es que le recomiende su jefe/a a un colega?",
      listaRes: [
        {
          idRelacion: 11,
          idPregunta: 27,
          idRespuesta: 1,
          respuesta: "Muy probable"
        },
        {
          idRelacion: 22,
          idPregunta: 27,
          idRespuesta: 2,
          respuesta: "Nada probable"
        }
      ]
    },
    {
      idEncuesta: 7,
      encuesta: "Encuesta2",
      idPregunta: 27,
      pregunta:
        "¿Qué tan fácil es obtener ayuda de su jefe/a cuando la necesita?",
      listaRes: [
        {
          idRelacion: 158,
          idPregunta: 130,
          idRespuesta: 76,
          respuesta: "Texto libre"
        }
      ]
    },
    {
      idEncuesta: 7,
      encuesta: "Encuesta2",
      idPregunta: 28,
      pregunta: "¿Qué tan disponible para los empleados esta su jefe?",
      listaRes: [
        {
          idRelacion: 88,
          idPregunta: 28,
          idRespuesta: 8,
          respuesta: "Nada disponible"
        },
        {
          idRelacion: 99,
          idPregunta: 28,
          idRespuesta: 9,
          respuesta: "Poco disponible"
        },
        {
          idRelacion: 1010,
          idPregunta: 28,
          idRespuesta: 10,
          respuesta: "Moderadamente disponible"
        },
        {
          idRelacion: 1111,
          idPregunta: 28,
          idRespuesta: 11,
          respuesta: "Muy disponible"
        },
        {
          idRelacion: 1212,
          idPregunta: 28,
          idRespuesta: 12,
          respuesta: "Extremadamente disponible"
        }
      ]
    }
  ];

  var [arrayPreguntas, setarrayPreguntas] = useState([]);
  const [respuestaIdRelacion, setRespuestaIdRelacion] = useState([]);

  var [arrayIdRelacion, setArrayIdRelacion] = useState([]);

  const [respuestaLibre, setRespuestaLibre] = useState([]);

  var [arrayRespuestaLibre, setArrayRespuestaLibre] = useState([]);

  const handleChange = (e) => {
    const { name, value } = e.target;

    setRespuestaIdRelacion((prevState) => ({
      ...prevState,
      idRelacion: parseInt(value),
      idPregunta: parseInt(name)
    }));
  };

  const onblurRespuesta = function () {
    arrayRespuestaLibre.push(respuestaLibre);
  };

  const onblurIdRelacion = function (e) {
    arrayPreguntas.push(respuestaIdRelacion);
    console.log(arrayPreguntas);

    arrayPreguntas = arrayPreguntas.filter(
      (thing, index, self) =>
        index === self.findIndex((t) => t && t.idPregunta === thing.idPregunta)
    );

    console.log(arrayPreguntas);
  };

  const guardar = (e) => {
    e.preventDefault();

    for (var i = 0; i < arrayPreguntas.length; i++) {
      arrayIdRelacion.push(arrayPreguntas[i].idRelacion);
      console.log(arrayIdRelacion);
    }

    if (arrayIdRelacion.length === 0) {
      return;
    }

    for (var j = 0; j < arrayIdRelacion.length; ++j) {
      respuestas.push({
        idRelacion: arrayIdRelacion[j],
        respuestaLibre: arrayRespuestaLibre[j]
      });
    }

    console.log(respuestas);
    //guardarRespuestas();
    respuestas = [];
  };

  return (
    <section style={{ display: "flex", justifyContent: "space-around" }}>
      <div>
        <form onSubmit={guardar}>
          <ol>
            {preguntas.map((item) => (
              <li key={item.id}>
                {item.pregunta}
                <ul className="list-group">
                  {item.listaRes.map((subitem) => (
                    <React.Fragment>
                      <li
                        name="opciones"
                        className="list-group"
                        key={subitem.idRelacion}
                      >
                        <>
                          <input
                            className="form-check-input"
                            type="radio"
                            name={subitem.idPregunta}
                            defaultValue={subitem.idRelacion}
                            /*  onChange={(e) =>
                              setRespuestaIdRelacion(e.target.value)
                            } */
                            onChange={handleChange}
                            onBlur={onblurIdRelacion}
                          ></input>
                          <label
                            className="form-check-label"
                            htmlFor="exampleRadios1"
                          >
                            {subitem.respuesta}
                          </label>
                        </>
                      </li>
                    </React.Fragment>
                  ))}
                  Obs.
                  <br />
                  <textarea
                    className="form-control mb-2"
                    type="text"
                    required
                    name="respuestaLibre"
                    autoComplete="off"
                    onChange={(e) => setRespuestaLibre(e.target.value)}
                    onBlur={onblurRespuesta}
                  ></textarea>
                </ul>
              </li>
            ))}
          </ol>
          <button
            className="btn btn-primary btn-sm active float-right btn-block"
            type="submit"
          >
            Guardar
          </button>
        </form>
      </div>
    </section>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

4
  • estuve pensando en algo asi, pero al ejecutar da un error, parece que en algún punto el array se limpia y da indefino , talvez te sirve de algo const onblurRespuesta = function () { let ultimo_objeto=null; if(arrayRespuestaLibre.length>0) for(var i=0;arrayRespuestaLibre.length;i++) { if(arrayRespuestaLibre && arrayRespuestaLibre[i].idRelacion===respuestaLibre.idRelacion) { ultimo_objeto=arrayRespuestaLibre[i]; } } if(ultimo_objeto) respuestaLibre.idRelacion=ultimo_objeto; arrayRespuestaLibre.push(respuestaLibre); }; el 11 oct. 2021 a las 17:48
  • Asi es marca error de un undefined @HeynerMartinez el 11 oct. 2021 a las 18:21
  • haz un filter al array por el id de pregunta si ya existe eliminala con splie y si no agregala... la verdad suena facil no se si es lo que buscas el 11 oct. 2021 a las 19:15
  • @CristianCamilo si es lo que busco pero no tengo idea de como hacer eso el 11 oct. 2021 a las 19:22

1 respuesta 1

0

No debes hacer un push debes jugar con los estados si quieres modificar un estado debes usar la funcion que lo setea no hacer uso del push directamente en el estado.

const onblurIdRelacion = function (e) {
    let newsAnswer = arrayPreguntas.filter(
      (p) => p.idPregunta !== respuestaIdRelacion.idPregunta
    );
    newsAnswer.push(respuestaIdRelacion);
    setarrayPreguntas(newsAnswer);
    console.log(arrayPreguntas);
  };

Te modifique la función onBLurIdrelacion el resto está igual

import React, { useState } from "react";
import ReactDOM from "react-dom";

export default function App() {
  var respuestas = [];

  const preguntas = [
    {
      idEncuesta: 7,
      encuesta: "Encuesta2 ",
      idPregunta: 26,
      pregunta: "¿Que tan probable es que le recomiende su jefe/a a un colega?",
      listaRes: [
        {
          idRelacion: 11,
          idPregunta: 27,
          idRespuesta: 1,
          respuesta: "Muy probable"
        },
        {
          idRelacion: 22,
          idPregunta: 27,
          idRespuesta: 2,
          respuesta: "Nada probable"
        }
      ]
    },
    {
      idEncuesta: 7,
      encuesta: "Encuesta2",
      idPregunta: 27,
      pregunta:
        "¿Qué tan fácil es obtener ayuda de su jefe/a cuando la necesita?",
      listaRes: [
        {
          idRelacion: 158,
          idPregunta: 130,
          idRespuesta: 76,
          respuesta: "Texto libre"
        }
      ]
    },
    {
      idEncuesta: 7,
      encuesta: "Encuesta2",
      idPregunta: 28,
      pregunta: "¿Qué tan disponible para los empleados esta su jefe?",
      listaRes: [
        {
          idRelacion: 88,
          idPregunta: 28,
          idRespuesta: 8,
          respuesta: "Nada disponible"
        },
        {
          idRelacion: 99,
          idPregunta: 28,
          idRespuesta: 9,
          respuesta: "Poco disponible"
        },
        {
          idRelacion: 1010,
          idPregunta: 28,
          idRespuesta: 10,
          respuesta: "Moderadamente disponible"
        },
        {
          idRelacion: 1111,
          idPregunta: 28,
          idRespuesta: 11,
          respuesta: "Muy disponible"
        },
        {
          idRelacion: 1212,
          idPregunta: 28,
          idRespuesta: 12,
          respuesta: "Extremadamente disponible"
        }
      ]
    }
  ];

  var [arrayPreguntas, setarrayPreguntas] = useState([]);
  const [respuestaIdRelacion, setRespuestaIdRelacion] = useState([]);

  var [arrayIdRelacion, setArrayIdRelacion] = useState([]);

  const [respuestaLibre, setRespuestaLibre] = useState([]);

  var [arrayRespuestaLibre, setArrayRespuestaLibre] = useState([]);

  const handleChange = (e) => {
    const { name, value } = e.target;

    setRespuestaIdRelacion((prevState) => ({
      ...prevState,
      idRelacion: parseInt(value),
      idPregunta: parseInt(name)
    }));
  };

  const onblurRespuesta = function () {
    arrayRespuestaLibre.push(respuestaLibre);
  };

  const onblurIdRelacion = function (e) {
    let newsAnswer = arrayPreguntas.filter(
      (p) => p.idPregunta !== respuestaIdRelacion.idPregunta
    );
    newsAnswer.push(respuestaIdRelacion);
    setarrayPreguntas(newsAnswer);
    console.log(arrayPreguntas);
  };

  const guardar = (e) => {
    e.preventDefault();

    for (var i = 0; i < arrayPreguntas.length; i++) {
      arrayIdRelacion.push(arrayPreguntas[i].idRelacion);
    }

    if (arrayIdRelacion.length === 0) {
      return;
    }

    for (var j = 0; j < arrayIdRelacion.length; ++j) {
      respuestas.push({
        idRelacion: arrayIdRelacion[j],
        respuestaLibre: arrayRespuestaLibre[j]
      });
    }

    console.log(respuestas);
    //guardarRespuestas();
    respuestas = [];
  };

  return (
    <section style={{ display: "flex", justifyContent: "space-around" }}>
      <div>
        <form onSubmit={guardar}>
          <ol>
            {preguntas.map((item) => (
              <li key={item.id}>
                {item.pregunta}
                <ul className="list-group">
                  {item.listaRes.map((subitem) => (
                    <React.Fragment>
                      <li
                        name="opciones"
                        className="list-group"
                        key={subitem.idRelacion}
                      >
                        <>
                          <input
                            className="form-check-input"
                            type="radio"
                            name={subitem.idPregunta}
                            defaultValue={subitem.idRelacion}
                            /*  onChange={(e) =>
                              setRespuestaIdRelacion(e.target.value)
                            } */
                            onChange={handleChange}
                            onBlur={onblurIdRelacion}
                          ></input>
                          <label
                            className="form-check-label"
                            htmlFor="exampleRadios1"
                          >
                            {subitem.respuesta}
                          </label>
                        </>
                      </li>
                    </React.Fragment>
                  ))}
                  Obs.
                  <br />
                  <textarea
                    className="form-control mb-2"
                    type="text"
                    required
                    name="respuestaLibre"
                    autoComplete="off"
                    onChange={(e) => setRespuestaLibre(e.target.value)}
                    onBlur={onblurRespuesta}
                  ></textarea>
                </ul>
              </li>
            ))}
          </ol>
          <button
            className="btn btn-primary btn-sm active float-right btn-block"
            type="submit"
          >
            Guardar
          </button>
        </form>
      </div>
    </section>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.