Skip to content

Commit

Permalink
Redux ok
Browse files Browse the repository at this point in the history
  • Loading branch information
Ignacio Peluaga committed Mar 7, 2021
1 parent 6400edf commit d7f7fc5
Show file tree
Hide file tree
Showing 7 changed files with 99 additions and 67 deletions.
31 changes: 25 additions & 6 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,34 @@ import Menu from './components/Menu'
import TopHeader from './components/TopHeader'
import MainNav from './components/MainNav'
import Introduction from './components/Introduction'
import UniversityList from './styledComponents/UniversityList'// no necesitan estado global de redux
import UniversityList from './styledComponents/UniversityList'// hasta este no necesitan estado global de redux
import FilterForm from './containers/FilterForm' //utiliza store de redux
import { Action, createStore } from 'redux';
import IGlobalState, { initialState } from './states/globalState'
import { Provider } from 'react-redux'
import { IAreaChangeAction, IResultsChangeAction, ITipoChangeAction, IUniChangeAction } from './actions/FilterFormActions';
import { FilterFormActions } from './actions/FilterFormActions'

//recibe un estado y una acción. Devuelve el resultado de aplicar al estado la acción
const reducer = (state: IGlobalState = initialState, action: Action) => {
const reducer = (state: IGlobalState = initialState, action: Action) => {
switch (action.type) {
case FilterFormActions.CHANGE_UNI: // aquí iria 'uni' pq está cambiando esa propiedad # TODO: usar enum # TODO: debe haber un case por cada una de las 4 acciones
const uniAction = action as IUniChangeAction;
return {...state, uni: uniAction.payload}

case FilterFormActions.CHANGE_AREA:
const areaAction = action as IAreaChangeAction;
return {...state, area: areaAction.payload}

case FilterFormActions.CHANGE_TIPO:
const tipoAction = action as ITipoChangeAction;
console.log(tipoAction.payload)
return {...state, tipo: tipoAction.payload}

case FilterFormActions.CHANGE_RESULTS:
const resultsAction = action as IResultsChangeAction;
return {...state, results: resultsAction.payload}
}
return state;
}

Expand All @@ -28,7 +48,7 @@ function App() {
<a id="mobile-trigger" href="https://www.distritounicoandaluz.org/#mob-menu"><i className="fa fa-bars"></i></a>
<Menu/>
<a id="mobile-trigger2" href="https://www.distritounicoandaluz.org/#mob-menu2"><i className="fa fa-bars"></i></a>
{/*REMOVED 1 FROM HERE*/}

</div>
<TopHeader/>
<header id="masthead" className="site-header" role="banner">
Expand Down Expand Up @@ -62,17 +82,16 @@ function App() {
pueden elegir todas las opciones académicas que ofrecen los siguientes
Establecimientos Universitarios Públicos de la Comunidad:</p>

{/* REFACTORING SHOULD START HERE # TODO: use redux and jss */}
{/* REFACTORING STARTS HERE */}

<UniversityList/>

<p>Mas info sobre el <strong>Distrito Unico Andaluz</strong>: <a href="https://www.juntadeandalucia.es/economiainnovacionyciencia/sguit/">https://www.juntadeandalucia.es/economiainnovacionyciencia/sguit/</a>#</p>

<FilterForm />

{/* REFACTORING SHOULD END HERE */}
{/* REFACTORING ENDS HERE */}


<div style={{ fontSize: "0px", height: "0px", lineHeight: "0px", margin: "0", padding: "0", clear: "both" }}>
</div>

Expand Down
21 changes: 21 additions & 0 deletions src/actions/FilterFormActions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Action } from 'redux'

export enum FilterFormActions {
CHANGE_UNI = "CHANGE_UNI",
CHANGE_AREA = "CHANGE_AREA",
CHANGE_TIPO = "CHANGE_TIPO",
CHANGE_RESULTS = "CHANGE_RESULTS",
}

export interface IUniChangeAction extends Action {
payload: string
}
export interface IAreaChangeAction extends Action {
payload: string
}
export interface ITipoChangeAction extends Action {
payload: string
}
export interface IResultsChangeAction extends Action {
payload: [string, string][]
}
73 changes: 23 additions & 50 deletions src/components/FilterForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,54 +3,34 @@ import * as React from 'react';
// DATOS
var data = require('./db.json');

interface IFilterFormState {
interface IFilterFormProps {
uni: string
tipo: string
setUni: (uni: string) => any;

area: string
setArea: (area: string) => any;

tipo: string
setTipo: (tipo: string) => any;

results: [string, string][]
setResults: (results: [string, string][]) => any;
}

class FilterForm extends React.Component<{}, IFilterFormState> {

constructor(props: {}) {
class FilterForm extends React.Component<IFilterFormProps, {}> {

constructor(props: IFilterFormProps) {
super(props);
this.state = {
uni: "Universidad de Sevilla",
tipo: "Máster",
area: "Ingeniería",
results: []
};
this.queryDB = this.queryDB.bind(this); // TODO: check
}

public setUni(event: React.ChangeEvent<HTMLSelectElement>) {
let newState = {
uni: event.target.value,
tipo: this.state.tipo,
area: this.state.area,
results: this.state.results
}
this.setState(newState);
this.queryDB = this.queryDB.bind(this)
}
public setArea(event: React.ChangeEvent<HTMLSelectElement>) {
let newState = {
uni: this.state.uni,
tipo: this.state.tipo,
area: event.target.value,
results: this.state.results
}
this.setState(newState);
}
public setTipo(event: React.ChangeEvent<HTMLSelectElement>) {
let newState = {
uni: this.state.uni,
tipo: event.target.value,
area: this.state.area,
results: this.state.results
}
this.setState(newState);
}


public queryDB() {

//var res = []
Expand All @@ -60,7 +40,7 @@ class FilterForm extends React.Component<{}, IFilterFormState> {
var obj = data[i];
console.log(obj);

if (obj["university"] === this.state.uni) {
if (obj["university"] === this.props.uni) {

var uniWeb = obj["web"]

Expand All @@ -75,32 +55,25 @@ class FilterForm extends React.Component<{}, IFilterFormState> {

//console.log(univ_degrees[j])

if (this.state.tipo === "Máster" && univ_degrees[j]["name"].includes("Máster") && this.state.area === univ_degrees[j]["area"]) {
if (this.props.tipo === "Máster" && univ_degrees[j]["name"].includes("Máster") && this.props.area === univ_degrees[j]["area"]) {
res.push([univ_degrees[j]["name"], uniWeb])
}
else if (this.state.tipo === "Grado" && !univ_degrees[j]["name"].includes("Máster") && this.state.area === univ_degrees[j]["area"]) {
else if (this.props.tipo === "Grado" && !univ_degrees[j]["name"].includes("Máster") && this.props.area === univ_degrees[j]["area"]) {
res.push([univ_degrees[j]["name"], uniWeb])
}
}
}
}
console.log(res);
let newState = {
uni: this.state.uni,
tipo: this.state.tipo,
area: this.state.area,
results: res
}
this.setState(newState);
this.props.setResults(res);
}

public render() {
console.log(this.props.tipo)
return (

<div>
<h3>Buscador de Titulaciones</h3>
<div><label>Universidad </label>
<select onChange={e => this.setUni(e)} >
<select onChange={(event) => this.props.setUni(event.target.value)} >
<option value="Universidad de Sevilla">Universidad de Sevilla</option>
<option value="Universidad de Almería">Universidad de Almería</option>
<option value="Universidad de Cádiz">Universidad de Cádiz</option>
Expand All @@ -113,22 +86,22 @@ class FilterForm extends React.Component<{}, IFilterFormState> {
</select></div>

<div style={{ marginTop: "5px" }}><label>Area </label>
<select onChange={e => this.setArea(e)} >
<select onChange={(event) => this.props.setArea(event.target.value)} >
<option value="Ingeniería">Ingenieria</option>
<option value="Ciencias">Ciencias</option>
<option value="Otros">Otras</option>
</select></div>

<div style={{ marginTop: "5px" }}><label>Tipo de Titulación</label>
<select onChange={e => this.setTipo(e)} >
<select onChange={(event) => this.props.setTipo(event.target.value)} >
<option value="Máster">Máster</option>
<option value="Grado">Grado</option>
</select></div>

<button style={{ marginTop: "15px" }} onClick={this.queryDB} type="button">Buscar</button>

<div style={{ marginTop: "15px" }}>
{this.state.results.map(degreeResult =>
{this.props.results.map(degreeResult =>
<div>
<p>{degreeResult[0]} <a target="_blank" rel="noreferrer" href={degreeResult[1]}>(Más Información)</a></p>
</div>
Expand Down
3 changes: 1 addition & 2 deletions src/components/UniversityList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,12 @@ export interface IUniversityListProps {
classes: IUniversityListClasses<string>;
}


class UniversityList extends React.Component<IUniversityListProps, {}> {

public render() {
return (

<div className={this.props.classes.wrapper}> {/* public/css/wrapper.css */}
<div className={this.props.classes.wrapper}> {/* era public/css/wrapper.css */}

<University wrapperItemCounter={"one"} href={"https://www.ual.es/"} title={"Universidad de Almería"} imgSrc={ualLogo} uniText={"<strong><a title=\"Universidad de Almeria\" href=\"https://www.distritounicoandaluz.org/universidad-de-almeria/\">UNIVERSIDAD DE ALMERÍA</a>:</strong> Creada por el Parlamento Andaluz en 1993. Es una de las universidades más jóvenes de España. Su oferta académica incluye más&nbsp;de 30 titulaciones, más de 37 programas de doctorado (9 de ellos con mención de calidad), 13 másteres oficiales y 12 másteres propios."} />

Expand Down
2 changes: 0 additions & 2 deletions src/components/db.json
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,6 @@
"university": "Universidad de Sevilla",
"web":"https://www.us.es/",
"degrees": [
{"name":"Máster Universitario en Automática, Robótica y Telemática (R.D.1393/07)","area":"Ingeniería"},
{"name":"Máster Universitario en Ingeniería Ambiental (R.D.1393/07)","area":"Ingeniería"},
{"name":"Máster Universitario en Economía y Desarrollo (R.D.1393/07)","area":"Otros"},
{"name":"Máster Universitario en Actividad Física y Calidad de Vida de Personas Adultas y Mayores (RD.1393/2007)","area":"Otros"},
{"name":"Máster Universitario en Sistemas de Energía Térmica (R.D.1393/07)","area":"Ciencias"},
Expand Down
29 changes: 25 additions & 4 deletions src/containers/FilterForm.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,33 @@
import { Dispatch } from 'redux';
import { connect } from 'react-redux';

import FilterForm from '../components/FilterForm';
import IGlobalState from '../states/globalState';
import { FilterFormActions } from '../actions/FilterFormActions'

const mapStateToProps = (state:IGlobalState) => {
return({university: state.uni}) //las propiedades del componente FilterForm
//crea esa propiedad a partir de la información del estado global
const mapStateToProps = (state: IGlobalState) => ({
uni: state.uni,
area: state.area,
tipo: state.tipo,
results: state.results
})

const mapDispatchToProps = (dispatch: Dispatch) => {
return {
setUni: (uni: string) => {
dispatch({ type: FilterFormActions.CHANGE_UNI, payload: uni });
},
setTipo: (tipo: string) => {
dispatch({ type: FilterFormActions.CHANGE_TIPO, payload: tipo });
},
setArea: (area: string) => {
dispatch({ type: FilterFormActions.CHANGE_AREA, payload: area });
},
setResults: (results: [string, string][]) => {
dispatch({ type: FilterFormActions.CHANGE_RESULTS, payload: results });
}
}
}

//Con esto, ese FilterForm recibe el store de forma automatica
export default connect(mapStateToProps)(FilterForm);
export default connect(mapStateToProps, mapDispatchToProps)(FilterForm);
7 changes: 4 additions & 3 deletions src/states/globalState.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
interface IGlobalState {
uni: string,
tipo: string,
area: string
area: string,
results: [string, string][]
}

export default IGlobalState;
Expand All @@ -10,6 +11,6 @@ export const initialState: IGlobalState = {
//estado inicial, definir a mano
uni: "Universidad de Sevilla",
tipo: "Máster",
area: "Ingeniería"

area: "Ingeniería",
results: []
}

0 comments on commit d7f7fc5

Please sign in to comment.