How to include multiple texts in an array in the same function?

Asked

Viewed 41 times

1

I’m trying to include in a array several messages that are in the same function. I receive some data and make some comparisons according to some requirements, resulting in a message that I need to display on the screen. That’s 26 situations altogether, I thought I’d save one array and make a .map() to display to the user. But since the comparisons are in the same function, I am not able to update the state of the array.

    const [messages, setMessages] = useState([])
    const calculateMan = () => {
        setOpen(true);
        let state = true
        //===========================================================================================================================================//
        ////- APOSENTADORIA POR IDADE URBANA DIREITO ADQUIRIDO ATÉ A DATA DA REFORMA (13.11.2019)
        if (age >= 65 && totalUrbanContri > 15) {
            setMessages([...messages, { content: 'Possível aposentadoria por idade urbana'}])
        } else {
            setMessages([...messages, { content: 'Não Possível aposentadoria por idade urbana'}])
        }
        //===========================================================================================================================================//
        //APOSENTADORIA POR IDADE HÍBRIDA DIREITO ADQUIRIDO ATÉ A DATA DA REFORMA (13.11.2019)
        if (age >= 65 && totalUrbanContri + totalRuralContri >= 15){
            setMessages([...messages, { content:'Possível aposentadoria por idade hibrida'}])
        } else {
            setMessages([...messages, { content:'Não possível aposentadoria por idade hibrida'}])
        }
        //===========================================================================================================================================//
        //APOSENTADORIA POR TEMPO DE CONTRIBUIÇÃO – DIREITO ADQUIRIDO ATÉ A DATA DA REFORMA (13.11.2019)
        if (totalUrbanContri >= 15) {
            let especial15 = totalEspecialQuinzeContri * 2.33 
            let especial20 = totalEspecialVinteContri * 1.75 
            let especial25 = totalEspecialVinteCincoContri * 1.40
            let totalAteReforma = totalUrbanContri + totalRuralContri + especial20 + especial25 + especial15 + totalProfessorContribuicao 
            if (totalAteReforma>= 35) {
                setMessages([...messages, { content: 'Apto a aposentadoria por tempo de contribuição'}])
            } else {
                setMessages([...messages, { content: 'Não apto a aposentadoria por tempo de contribuição'}])
            }
        }
    }

Here there are only 3 conditions, but altogether there are 26. The way it is there, when I make one map() the result is always the last element of the array for every time I click.

                    <button className="px-4 py-2 text-white bg-green-500 rounded-md" onClick={()=> data.gender == 1 ? calculateMan() : calculateWoman()}>
                        Calcular
                    </button>

I am displaying the results in a Modal, but at each click it inserts only the last message on the screen. It means that it rotates all 26 situations and saves in messages only the result of the last situation.

      const body = (
        <div style= {{justifyContent: 'center', alignItems: 'center', width: 'auto', height: '600px', background: '#fff'}}>
            {console.log(messages)}
            {messages !== [] && messages.map(message => (
                <div key={message.content}> 
                    {message.content}
                </div>
        ))}
        </div>
      );
  • Have you tried using . push? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

  • I tried with . push also and did not give, but I do not know if I did something wrong or does not fit the situation.

1 answer

0


There is the simplest solution that is to create a array and added the values and finally update the state of the component, the more complex solution also gives, but maybe it is complicating what could be simple, I will create the two examples so that you have the possibility to choose in your project:

Simple example (only happens once component update and performance is better)

function App() {
 const age = 18 
 const [messages, setMessages] = React.useState([]); 
 const handleCalculate = () => {
  const m = [];
  if (age <= 18) {
    m.push({content: "Menor que 18"});
  }
  if (age / 2 === 9) {
    m.push({content: "É 9"});
  }
  if (age / 3 !== 9) {
    m.push({content: "É diferente 9"});
  }
  setMessages(state => [...state, ...m]);
 }
 return (
  <div>
    <ul>
      {messages.length > 0 && messages.map((x,i) => (
        <li key={i}>{x.content}</li>
      ))}
    </ul>
    <button onClick={handleCalculate}>Acionar</button>
  </div>
 )
}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root">Carregando ...</div>

Direct example in the state (it is complicated because the component is updated to each item contemplated in the state of the variable messages):

function App() {
 const age = 18 
 const [messages, setMessages] = React.useState([]); 
 const handleCalculate = () => {
  if (age <= 18) {
    setMessages(state => [...state, {content: "Menor que 18"}]);
  }
  if (age / 2 === 9) {
    setMessages(state => [...state, {content: "É 9"}]);
  }
  if (age / 3 !== 9) {
    setMessages(state => [...state, {content: "É diferente 9"}]);
  }
 }
 return (
  <div>
    <ul>
      {messages.length > 0 && messages.map((x,i) => (
        <li key={i}>{x.content}</li>
      ))}
    </ul>
    <button onClick={handleCalculate}>Acionar</button>
  </div>
 )
}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root">Carregando ...</div>

  • 1

    It worked out my friend! And in the simplest way :)) Thank you very much for your help!!

  • If it is useful, tick as answer to your question @Gabrielsouza

Browser other questions tagged

You are not signed in. Login or sign up in order to post.