Skip to content

Instantly share code, notes, and snippets.

@Angelmmiguel
Created April 4, 2023 17:09
Show Gist options
  • Save Angelmmiguel/6108f4c0f7a78383964a0ce34c8f0964 to your computer and use it in GitHub Desktop.
Save Angelmmiguel/6108f4c0f7a78383964a0ce34c8f0964 to your computer and use it in GitHub Desktop.
Practica Curso React
import { useState, useContext, useEffect } from "react"
import { DEFAULT_STATE } from "../constants/form";
import "../styles/Form.css";
import useApi from "../hooks/useApi";
import Token from "../contexts/token";
const Register = () => {
const token = useContext(Token);
console.log("en Register");
const [formState, setFormState] = useState(DEFAULT_STATE);
// Devolvemos una funcion para modificar una parte del estado! (pendiente revisar comentario)
const onChange = (key) => {
return (e) => setFormState({
...formState,
[key]: e.target.value
});
}
const registerRequest = useApi();
// [Angel] Los métodos que responden a un evento siempre
// reciben el objeto "Event" como parámetro
const signIn = (e) => {
// [Angel] Evitamos que el navegador lance la petición contra el servidor
e.preventDefault();
console.log("*** en Register-signIn-ini");
registerRequest.updateRequest({url: "/api/register", method: "POST", body: {username: formState.username, password: formState.password}});
// registerRequest.updateParams("/api/register", "POST", {username: formState.username, password: formState.password});
// registerRequest.updateParams("/api/register", "POST", "", JSON.stringify({username: formState.username, password: formState.password}));
// registerRequest.updateParams("/api/register", "POST", "", JSON.stringify({username: "Usu", password: "123"}));
};
useEffect( () => {
if (registerRequest.data && token.current == ""){
console.log("*** en Register-con datos de respuesta. token en data: "+registerRequest.data.token);
token.update(registerRequest.data.token);
console.log("*** en Register-con datos de respuesta. token.current: "+token.current);
}
},[registerRequest]
);
return <div className="row">
<div className="col-6">
<form onSubmit={signIn}>
{/* <form onSubmit={signIn()}> */}
{/* <form onSubmit={onSubmit}> */}
<br/><br/>
<h1>
<label htmlFor="username">Usuario: </label>
<input id="username" type="text" value={formState.username} onChange={onChange("username")} />
</h1>
<br/>
<h1>
<label htmlFor="password">Contraseña: </label>
<input id="password" type="password" value={formState.password} onChange={onChange("password")} />
</h1>
<br/>
<input type="submit" value="Crear cuenta" />
{/* <button onClick={signIn}>Crear cuenta</button> */}
{/* <button>Crear cuenta</button> */}
</form>
</div>
</div>
}
export default Register;
import { useMemo, useEffect, useState, useContext } from "react";
import Token from "../contexts/token";
// Hook para acceder a la API
//
const useApi = () => {
// const [url, setUrl] = useState("");
// const [method, setMethod] = useState(null);
// const [requestBody, setRequestBody] = useState({});
const [data, setData] = useState(null);
const [error, setError] = useState(null);
// const [performRequest, setPerformRequest] = useState(false);
const [request, setRequest] = useState({});
const token = useContext(Token);
const updateRequest = (newRequest) => {
setRequest(newRequest);
// setPerformRequest(true);
}
useEffect(() => {
setError("");
if (request && request.method && request.url && request.body) {
const config = {
method: request.method,
headers: {},
// [Angel] En este caso faltaba el stringify
body: JSON.stringify(request.body)
}
config.headers["Content-Type"] = "application/json"; // forma alternativa, pendiente hacerlo dinamico para resto peticiones
if (token.current && token.current != "") {
config.headers["api-token"] = token.current;
}
// Realizamos la llamada al servidor
fetch(request.url, config)
.then((res) => res.json())
.then((json) => {
if (json.error != null) {
setError(json.error);
} else {
setData(json);
}
});
}
// [Angel] Si escuchamos a "token", cuando este cambie se volverá a
// a lanzar la petición
}, [request]);
return {
data,
error,
updateRequest
};
};
export default useApi;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment