Home > OS >  How can i setState for color change
How can i setState for color change

Time:02-18

I already have the condition, but i need to set the state, if i setColor on the if method, give me error- Too many re-renders. React limits the number of renders to prevent an infinite loop.

State:

const [color, setColor] = useState();

Map:

 {data.map((doc) => {
    let verificacao = "";

    if (doc.status === "Não Necessário") {
      verificacao = "Proxima Verificação:";
      setColor(true)

    } else if (doc.status === "Verificado e Conforme") {
      verificacao = "Data:";
      setColor(false)

    } else {
      console.log("ERRO");
    }

    return (

The span i want to change the color:

   <div className="row">
                <div className="pontos">
                  <span className={color ? "red" : "green"}>
                    {doc.status}
                  </span>
                  <span className="data-status">{verificacao}</span>
                  {JSON.stringify(
                    doc.dateVerificado
                      .toDate()
                      .toISOString()
                      .replace(/T.*/, "")
                      .split("-")
                      .reverse()
                      .join("-")
                  )}
                </div>
              </div>

Full Code:

import React, { useEffect, useState } from "react";
import { Button } from "react-bootstrap";
import ManutencaoDataService from 
"../../Services/ManutecaoDataService";
import "./ManutencaoInfo.css";

const ManutencaoInfo = ({ getDataId }) => {
const [data, setData] = useState([]);
const [color, setColor] = useState();

 useEffect(() => {

  getData();
  return () => {
   setData([]);
 };
}, []);

const getData = async () => {
  const data = await ManutencaoDataService.getAllData();
  console.log(data.docs);
  setData(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
};

const deleteHandler = async (id) => {
  await ManutencaoDataService.deleteData(id);
  getData();
 };


return (
<>
  <div className=" container mb-2">
    <Button variant="dark edit" onClick={getData}>
      Atualizar Lista
    </Button>
  </div>

  {/* <pre>{JSON.stringify(books, undefined, 2)}</pre>} */}

  {data.map((doc) => {
    let verificacao = "";

    if (doc.status === "Não Necessário") {
      verificacao = "Proxima Verificação:";
      setColor(true)
     
    } else if (doc.status === "Verificado e Conforme") {
      verificacao = "Data:";
      setColor(false)
     
    } else {
      console.log("ERRO");
    }

    return (
      <div key={doc.id} className="container-principal">
        <div className="container">
          <div className="row relatorio">
            <div className="col">
              <div className="departamento">
                <h3>{doc.departamentos}</h3>
              </div>
            </div>
          </div>
          <div className="row detalhes">
            <div className="col">
              <div className="row">
                <div className="pontos">
                  <span className="identificacao">Equipamento: 
                </span>
                  {doc.equipamentos}
                </div>
              </div>
              <div className="row">
                <div className="pontos">
                  <span className="identificacao">Responsável: 
               </span>
                  {doc.responsaveis}
                </div>
              </div>
              <div className="row">
                <div className="pontos">
                  <span className="codigo">{doc.codigos.codigo} 
                </span>
                  <span className="tipo">{doc.tipo}</span>
                </div>
              </div>
            </div>
            <div className="col ">
              <div className="row">
                <div className="pontos">
                  <span className="identificacao">Data Manutenção: 
                </span>
                  {JSON.stringify(
                    doc.dateManutencao
                      .toDate()
                      .toISOString()
                      .replace(/T.*/, "")
                      .split("-")
                      .reverse()
                      .join("-")
                  )}
                </div>
              </div>
              <div className="row">
                <div className="pontos">
                  <span className={color ? "red" : "green"}>
                    {doc.status}
                  </span>
                  <span className="data-status">{verificacao}</span>
                  {JSON.stringify(
                    doc.dateVerificado
                      .toDate()
                      .toISOString()
                      .replace(/T.*/, "")
                      .split("-")
                      .reverse()
                      .join("-")
                  )}
                </div>
              </div>
              <div className="row">
                <div className="pontos">{doc.codigos.observacoes} 
               </div>
              </div>
            </div>
          </div>
          <div className="row botoes">
            <div className="col">
              <span className="botao-editar">
                <Button
                  variant="secondary"
                  className="edit"
                  onClick={(e) => getDataId(doc.id)}
                >
                  Editar
                </Button>
              </span>
              <span className="botao-apagar">
                <Button
                  variant="danger"
                  className="delete"
                  onClick={(e) => deleteHandler(doc.id)}
                >
                  Apagar
                </Button>
              </span>
            </div>
          </div>
        </div>
      </div>
    );
  })}
</>
  );
 };

  export default ManutencaoInfo;

CodePudding user response:

Instead of using state, I would recommend using doc's status property for using the correct CSS class like this:

    <span className={doc.status === "Não Necessário" ? "red" : "green"}>
        {doc.status}
    </span>

CodePudding user response:

import React, { useEffect, useState } from "react";
import { Button } from "react-bootstrap";
import ManutencaoDataService from 
"../../Services/ManutecaoDataService";
import "./ManutencaoInfo.css";
import classNames from 'classnames';

const ManutencaoInfo = ({ getDataId }) => {
const [data, setData] = useState([]); 

 useEffect(() => {
  getData();
}, []);

const getData = async () => {
  const data = await ManutencaoDataService.getAllData();
  console.log(data.docs);
  setData(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
}

return (
<>
   ...

  {data.map((doc) => {
    return (
      <div key={doc.id} className="container-principal">
        <div className="container">
           ...
          <div className="row detalhes">
            ...
            <div className="col ">
               ...
              <div className="row">
                <div className="pontos">
                  <span className={classNames({red: doc.status === "Não Necessário", green:doc.status === "Verificado e Conforme" })}>
                    {doc.status}
                  </span>
                  <span className="data-status">{
 doc.status === "Não Necessário" ? "Proxima Verificação:" : doc.status === "Verificado e Conforme" ? "Data:" :""
}</span>
                 ....
                </div>
              </div>
               ....
            </div>
          </div>
           ...
        </div>
      </div>
    );
  })}
</>
  );
 };

  export default ManutencaoInfo;

create a new component which renders inside the map function, it will be better to maintain

CodePudding user response:

I think you are overcomplicating it with introducing state variable. You can just use local variable in your function like this:

// Remove this state
// const [color, setColor] = useState();

{data.map((doc) => {
    let verificacao = "";
    let color; // add this var

    if (doc.status === "Não Necessário") {
      verificacao = "Proxima Verificação:";
      color = 'red' // changed
    } else if (doc.status === "Verificado e Conforme") {
      verificacao = "Data:";
      color = 'green' // changed
    } else {
      console.log("ERRO");
    }

    return (
       // ...
       <span className={color}> {/* changed */}
          {doc.status}
       </span>
       // ...
    )
  • Related