How to set a state that is in a constant with React with a function

Asked

Viewed 29 times

1

I have the following code snippet:

const [aulas, setAulas] = React.useState([{
 id:1,
 title: 'Aula 1',
 descricao: 'Matemática',
}, {
 id:2,
 title: 'Aula 2',
 descricao: 'Portugues',
}])
 function addAula(aula) {
  // aqui eu precisaria atualizar o estado de 'aulas' com uma nova aula.
 }
 return null
}

However I do not know how I could use a function to set the state and update it, just using this function.

If you can help, thank you, I’m starting in React and learning the principles of statehood yet.

  • Can you explain more about what you want to show on this page/app? what it does addAula? as it should show in html?

1 answer

0

The function setAulas should be the only way to update the aulas.

For example, with setAulas(novoObjetoAulas).

Here is a complete example, with demonstration in Codepen:

function Component() {
  const defaultObject = [
    {
      id:1,
      title: 'Aula 1',
      descricao: 'Matemática',
    },
    {
      id:2,
      title: 'Aula 2',
      descricao: 'Portugues',
    }
  ]

  const [aulas, setAulas] = React.useState(defaultObject)
  const [id, setId] = React.useState(3)

  function addAula(aula) {
    const atualizacao = [...aulas, aula]
    setAulas(atualizacao)
  }

  function handleClick(event) {
    const aula = {
      id: id,
      title: 'Título qualquer que vc pode controlar',
      descricao: 'Descrição qualquer que vc pode controlar',
    }

    setId(id + 1)
    addAula(aula)
  }

  return (
    <div>
      <button onClick={handleClick}>
        Adicionar aula
      </button>

      <ul>
      {
        aulas.map(item => {
          const {id, title, descricao} = item

          return (
            <li>
              <b>id</b> = {id}<br/>
              <b>title</b> = {title}<br/>
              <b>descricao</b> = {descricao}
            </li>
          )
        })
      }
      </ul>
    </div>
  )
}

Browser other questions tagged

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