Skip to content

Commit

Permalink
Implementing custom hook: useOnInit (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
mosjim authored Nov 10, 2023
1 parent f66008d commit 41c606c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
18 changes: 10 additions & 8 deletions src/components/MailReader.jsx
Original file line number Diff line number Diff line change
@@ -1,39 +1,41 @@
import { Button } from 'primereact/button'
import { InputText } from 'primereact/inputtext'
import { Panel } from 'primereact/panel'
import { useEffect, useState } from 'react'
import { useState } from 'react'

import { mailService } from '../service/mailService'
import { MailsGrid } from './MailsGrid'
import { MailsSummary } from './MailsSummary'
import { useOnInit } from '../customHooks/hooks'

export const MailReader = () => {
const [textoBusqueda, setTextoBusqueda] = useState('')
const [mails, setMails] = useState([])


useOnInit(()=>buscarMails(textoBusqueda))

const leerMail = async (mail) => {
mail.leer()
// no es necesario hacer esto, pero ojo con avisar al backend
await mailService.actualizar(mail)
setMails([...mails])

// setMails(mails.map((mail) =>
// mail.id === idLeido ? mail.leer() : mail
// ))
// leer debería ser una función que devuelve un nuevo mail
}

// Variante más simple
const buscarMails = async (textoBusquedaNuevo) => {
setTextoBusqueda(textoBusquedaNuevo)
const nuevosMails = await mailService.getMails(textoBusquedaNuevo)
setMails(nuevosMails)
}




useEffect(() => {
buscarMails(textoBusqueda)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])

// otra variante más rebuscada
// es que el InputText tenga el onchange definido como onChange={(event) => setTextoBusqueda(event.target.value)}
Expand Down
7 changes: 7 additions & 0 deletions src/customHooks/hooks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { useEffect } from "react"

export const useOnInit = (initialCallBack)=>{
useEffect(() => {
initialCallBack()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])}

0 comments on commit 41c606c

Please sign in to comment.