How to Update a Component with Hooks

Asked

Viewed 19 times

-1

I have a form that when saving a record should update the list of users. When it was in the same component the list would update normally. Now I need to refresh the page to get the updated list. I will still create the buttons to edit and delete, I have an idea. I’m using React-hook-Forms for validation, but I got caught up in it. I need help, I’m learning how to work with functional components in React. Thanks in advance and follow the code:

userCrud.jsx

import Main from "../template/Main";
import React, { useState, useEffect} from "react";
import axios from 'axios';
import { useForm } from "react-hook-form";
import { yupResolver } from '@hookform/resolvers/yup';
import urls from "../../const/const";

import * as Yup from 'yup';

import UserList from "./userComponents/userList";

/*
    rules
    - [DONE] create an initial state what have to be called when user hits clear button .
    - [DONE] define a url user const
    - [DONE] use yup for validate all fields
    - set a list with all registered forms
    - functions of form:
    >> clear- set state to initial
    >> save: if exist a user.id? put: post; build a url and call axios to finish the job; data> update the list on state

*/



const headerProps = {
    title:"Cadastro de Funcionários",
    subtitle:"Cadastro, Exclusão, Atualização de Dados e Listagem"
}

// api rest url
const urlUsers = urls.users;

// initial state of the inputs
const initialState = {
    user:{
        firstName:'',
        lastName:'',         
    },
  
}

// input validators
const userFormSchema = Yup.object().shape({
    firstName: Yup.string().min(2, 'Muito Curto').max(20, 'Muito Longo').required('Campo Obrigatório'),
    lastName:Yup.string().min(2, 'Muito Curto').max(20, 'Muito Longo').required('Campo Obrigatório'),
    
});


export default function UserCrud () {

    const { register,reset, handleSubmit, setValue, formState:{ errors } } = useForm(
                                                                            {   defaultValues:initialState.user,
                                                                                resolver:yupResolver(userFormSchema),
                                                                                mode:"onBlur",
                                                                            });

                                                    
    const [userList, setUserList] = useState([]);

// busca a lista
    useEffect(()=> {
        axios(urlUsers)
            .then((resp=>{
                setUserList(resp.data)
            })
        )
    },[] );

    const updateList = (user) =>{
        const list = userList;
        list.filter((u) => u.id !== user.id)
        list.unshift(user)
        return setUserList(list);
    }
                             
                                                                            
    const clear = () => {
        reset({initialState})
    }

    //post -> save put-> update with id
    const save = (data) => {
        const method = data.id ? 'put' : 'post'
        const url = data.id ? `${urlUsers}/${data.id}`:urlUsers;
        axios[method](url, data)
            .then(resp =>{
                return updateList(resp.data)
            })
            .catch((error) => {
                console.log('error occured when saving. Try later.Error: ' + error)
            })
    }

        // set state with user data
    
    // criar formulário

    const FormUser = () => {
    return(

        <form 
            onSubmit={handleSubmit(save)}
        >
            <div className="row">
                <div className="col-12 col-md-3">
                    <div className="form-group">
                        <label htmlFor="firstName">Nome</label>
                        <input type="text" name="firstName"  className="form-control" {...register("firstName")} />
                        <p className="text-danger">{errors.firstName?.message}</p>
                    </div>
                </div>
            </div>

            <div className="row">
                <div className="col-12 col-md-3">
                    <div className="form-group">
                        <label htmlFor="lastName">Sobrenome</label>
                        <input type="text" name="lastName"   className="form-control" {...register("lastName")} />
                        <p className="text-danger">{errors.lastName?.message}</p>
                    </div>
                </div>
            </div>

            <hr className="col-12 col-md-2" />

            <div className="row">
                <div className="col-12 col-md-3">
                    
                    <button type="submit" className="btn btn-primary m-2">
                        Cadastrar
                    </button>

                    <button  className="btn btn-info" onClick ={clear}>
                        Limpar
                    </button>
                </div>
            </div>
        </form>
        

    )
}
    return(
        <Main {...headerProps}> 
            <div className="row">
            <FormUser/>
            <UserList list = {userList}/>     
            </div>        
        </Main>
    )
}

userlist.jsx

import React , { useState, useEffect} from "react";
import { Link } from 'react-router-dom';



const UserList= (props) =>{
    const { list } = props;
    console.log({list})
    return(
        <div className="col-12 col-md-8">
            <table className="table">
            <thead className="thead">
                <tr>
                    <th>Nome</th>
                    <th>Sobrenome</th>
                </tr>
            </thead>
            <tbody>
               
            {!!list && list.map((user, key) => (
                <tr key={key}>
                <td>{user.firstName}</td>
                <td>{user.lastName}</td>
            </tr>
            ))}
        
            </tbody>
        </table>
        </div>
    )
}

export default UserList;

App.jsx

import { HashRouter} from 'react-router-dom';
import Routes from './Routes';

import Logo from'../components/template/Logo';
import Nav from '../components/template/Nav';
import Footer from '../components/template/Footer';

const App = props =>

    <HashRouter>
        <div className="app">
            <Logo/>
            <Nav/>
            <Routes />
            <Footer/>
        </div>
    </HashRouter>
    

export default App
No answers

Browser other questions tagged

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