React: instalación

Tenemos dos maneras de ejecutar código en react. La más sencilla es incorporar los archivos a nuestra página con script:

 <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
  <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

La otra es instalar node y crear un archivo react:

https://nodejs.org/es/

Después instalar la posibilidad de react:

C:\Users\Your Name>npm install -g create-react-app

Y después crearla:

C:\Users\Your Name>npx create-react-app miappreact

Para ejecutar:

cd miappreact
npm start

Usar callback en promesas

Un ejemplo de cómo podemos pasar una función como parámetro para ejecutarla como callback:

import {getJSON,postJSON} from './peticiones.js';

function getCategorias(funcion) {
    getJSON("https://localhost:44333/api/Categories")
            .then(data => {console.log(data);funcion()})
            .catch(error => console.log(error));
}


function saludo(){
    console.log("hola");
}
getCategorias(saludo);

Ejemplo import-export

Peticiones:

async function getJSON(url) {
    const res = await fetch(url);

    if (!res.ok) {
        throw new Error(res.status); // 404
    }

    const data = await res.json();
    return data;
}

async function postJSON(url, obj) {
    const options = {
        method: 'POST',
        body: JSON.stringify(obj),
        headers: {
            'Content-Type': 'application/json'
        }
    };
    const res = await fetch(url,options);

    if (!res.ok) {
        throw new Error(res.status); // 404
    }

    const data = await res.json();
    return data;
}

export {getJSON, postJSON}

Categorías:

import {getJSON,postJSON} from './peticiones.js';

function getCategorias() {
    getJSON("https://localhost:44333/api/Categories")
            .then(data => console.log(data))
            .catch(error => console.log(error));
}

function addCategorias(categoria) {
    postJSON("https://localhost:44333/api/Categories",categoria)
            .then(data => console.log(data))
            .catch(error => console.log(error));
}
getCategorias();
addCategorias({"nombre":"doom","descripcion":"MATA"});

Ejercicio Fetch+API

Vamos a crear una web para hacer el mantenimiento de una tabla usando fetch.

Podéis usar la API que queráis pero yo os pongo aquí como debería ser en el caso del comic:

Todas las acciones se ejecutarán usando fetch.

Evitar error CORS

Ponemos lo siguiente en nuestra API:

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddDbContext<Contexto>(options =>
                   options.UseSqlServer(Configuration.GetConnectionString("MVCBasicContext")));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            app.UseCors("MyPolicy");
            app.UseHttpsRedirection();
            app.UseMvc();
        }

Ejemplo acceso a web api

<script>

    fetch("https://localhost:44339/api/Alumnoes").then(resp => resp.json())
        .then(data => {
            for (alumno of data) {
                console.log(alumno.id + "-" + alumno.nombre + "-" + alumno.nota);
            }
        })

    let alumno = { nombre: "Firulai", nota: 8 };
    let params = {
        method: 'POST',
        body: JSON.stringify(alumno),
        headers: {
            "Content-type": "application/json; charset=UTF-8"
        }
    };
    fetch('https://localhost:44339/api/Alumnoes', params)
        .then(response => response.json())
        .then(json => console.log(json))

    alumno = { id: 9, nombre: "Firulai", nota: 6 };
    params = {
        method: 'PUT',
        body: JSON.stringify(alumno),
        headers: {
            "Content-type": "application/json; charset=UTF-8"
        }
    };
    fetch('https://localhost:44339/api/Alumnoes/9', params)
        .then(response => response.json())
        .then(json => console.log(json))
        .catch(error => console.log(error));

    params = {
        method: 'DELETE',
        headers: {
            "Content-type": "application/json; charset=UTF-8"
        }
    };
    fetch('https://localhost:44339/api/Alumnoes/13', params)
        .then(response => response.json())
        .then(json => console.log(json))
        .catch(error => console.log(error));
</script>

Ejercicio usuarios

En la siguiente url:
https://randomuser.me/api/?results=3
Nos devuelve información aleatoria sobre usuarios.
Vamos a crear una web que al pulsar un botón nos pida por fetch a esa web 3 usuarios y nos muestre su nombre y su foto.