How to update GRUD status?

Asked

Viewed 65 times

1

How do I update the status ?

How do I click register and update the screen on time, and when to click X it delete and also update the page on time. I’m not getting, I have to give an update on the manual page.

Personal API is a json file and was used json-server to simulate. Exercise also needs to use Typescript.

follows the code.

import React, { useEffect, useRef, useState } from 'react';
import './App.css';
import axios from 'axios'

function App() {

  const [usuarios, setUsuarios] = useState<any>([])

  const inputNome = useRef<HTMLInputElement>(null)
  const inputIdade = useRef<HTMLInputElement>(null)
  const inputEmpresa = useRef<HTMLInputElement>(null)
  const inputTelefone = useRef<HTMLInputElement>(null)

  const mostraUsuarios = () => {
    axios.get("http://localhost:4000/usuarios")
      .then(resposta => setUsuarios(resposta.data))
  }

  const enviarCadastro = () => {

    const requisicao = {
      name: inputNome.current?.value,
      age: inputIdade.current?.value,
      company: inputEmpresa.current?.value,
      phone: inputTelefone.current?.value
    }

    axios.post("http://localhost:4000/usuarios", requisicao)
    mostraUsuarios()
  }

  useEffect(() => {
    mostraUsuarios()
  }, [])

  const deletarUsuario = (id: any) => {
    axios.delete(`http://localhost:4000/usuarios/${id}`)
    mostraUsuarios()
  }

  return (
    <div className="App">
      <input type="text" placeholder="Nome" ref={inputNome} />
      <input type="text" placeholder="Idade" ref={inputIdade} />
      <input type="text" placeholder="Empresa" ref={inputEmpresa} />
      <input type="text" placeholder="Telefone" ref={inputTelefone} />
      <button onClick={enviarCadastro}>Cadastrar</button>

      <br/>

      <ul>
        
        { usuarios !== null && 
          usuarios.map((item: any) => (
            <li key={item.id}>{item.name}  <button onClick={() => deletarUsuario(item.id)}>X</button></li>
          ))
        }
      </ul>
    </div>
  );
}

export default App;

  • the Aces in enviarCadastro is running at the same time as the mostrarUsuarios needs one first then the other must be that your problem the update in hits with the cadre made?

  • All right Novic, then I want at the time click register that it shows on the screen already the name , and when you click X already delete the user from the screen. I’m lost how to do this, if you can help me, and thanks for the tip.

  • Could someone help me update the status and already show it on the screen ?. The way I did with you is only on the Google manual button.

  • axios.post("http://localhost:4000/usuarios" this return something of the back end?

  • It’s all right, Novic. So this post is adding in the API, let’s assume you type a name and when you click on register it adds in the API, but I need it to show on the screen tb, I just can’t. The way it is in the code there I need to recharge the page on Google to appear.

  • along those lines axios.post("http://localhost:4000/usuarios", requisicao) place axios.post("http://localhost:4000/usuarios", requisicao).then(() => {mostraUsuarios()}) and remove from the last line mostraUsuarios()

  • I tried here Novic, but it didn’t work out either.

  • what happens in reality, what gives of errors? already looked at the console?

Show 3 more comments

1 answer

1


I generated a minimal example and it worked practically with your code, I made a change enviarCadastro that at the time of insertion and on return is identified if the statusreturn 201 that says the record was created and so I used the return data to update the list, example:

import React, { FormEvent, useEffect, useRef, useState } from 'react';
import axios from 'axios';

interface IUser {
  id?: number;
  name?: string;
  age?: number;
  company?: string;
  phone?: string;
}

function User() {
  const [usuarios, setUsuarios] = useState<IUser[]>([]);

  const inputNome = useRef<HTMLInputElement>(null);
  const inputIdade = useRef<HTMLInputElement>(null);
  const inputEmpresa = useRef<HTMLInputElement>(null);
  const inputTelefone = useRef<HTMLInputElement>(null);

  const mostraUsuarios = () => {
    axios
      .get('http://localhost:4000/usuarios')
      .then((resposta) => setUsuarios(resposta.data));
  };

  const deleteUsuario = (id?: number) => {
    axios.delete(`http://localhost:4000/usuarios/${id}`).then(() => {
      setUsuarios(usuarios.filter((x) => x.id !== id));
    });
  };

  const enviarCadastro = (e: FormEvent) => {
    e.preventDefault();
    const requisicao: IUser = {
      name: inputNome.current?.value,
      age: parseInt(inputIdade.current?.value || '0'),
      company: inputEmpresa.current?.value,
      phone: inputTelefone.current?.value,
    };
    axios
      .post('http://localhost:4000/usuarios', requisicao)
      .then((response) => {
        if (response.status === 201) {
          setUsuarios((state) => [...state, { ...response.data }]);
        }
      });
  };

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

  return (
    <div>
      <form>
        <input type="text" placeholder="Nome" ref={inputNome} />
        <input type="text" placeholder="Idade" ref={inputIdade} />
        <input type="text" placeholder="Empresa" ref={inputEmpresa} />
        <input type="text" placeholder="Telefone" ref={inputTelefone} />
        <button onClick={enviarCadastro}>Cadastrar</button>
      </form>
      <div>
        {usuarios &&
          usuarios.map((u, i) => (
            <div key={i}>
              {u.name} - {u.company} - {u.age} - {u.phone}
              <button onClick={() => deleteUsuario(u.id)}>Excluir</button>
            </div>
          ))}
      </div>
    </div>
  );
}

export default User;
  • All right Novic, it did work to register and update the page. I just couldn’t do it in deleting , I tried to use the same that you did in registering and it didn’t work.

  • @daniel did also delete, worth remembering that there are several ways to do this

  • Thank you, Novic, for your help. I’m doing another project but this mess with Redux, it’s kind of big, as I do to create a question here, I won’t be able to put all the code here. The doubt is how to update the Redux state to render the screen.

  • Create another @daniel question with as little information as possible!

  • Blz, thanks for your help here.

Browser other questions tagged

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