0

Estoy realizando un ejercicio que consiste en mostrar por pantalla tanto imágenes como autores.

Estas imágenes están alojadas en un json-server (La ruta de la imagen).

courses.json

{
    "courses": [
        {
            "id": 1,
            "title": "AI for Everyone",
            "authors": [1],
            "level": "Introductory",
            "courses": 5
        },
        {
            "id": 2,
            "title": "Deep Learning Specialization",
            "authors": [1, 2, 3],
            "level": "Intermediate",
            "courses": 5
        },
        {
            "id": 3,
            "title": "Natural Language Processing Specialization",
            "authors": [3, 4, 5],
            "level": "Intermediate",
            "courses": 4
        },
        {
            "id": 4,
            "title": "AI for Medicine Specialization",
            "authors": [6, 7, 8, 5],
            "level": "Intermediate",
            "courses": 3
        },
        {
            "id": 5,
            "title": "TensorFlow: Data and Deployment Specialization",
            "authors": [9],
            "level": "Intermediate",
            "courses": 4
        },
        {
            "id": 6,
            "title": "TensorFlow Developer Professional Certificate",
            "authors": [9],
            "level": "Intermediate",
            "courses": 4
        },
        {
            "id": 7,
            "title": "Generative Adversarial Networks (GANs) Specialization",
            "authors": [10, 11, 12],
            "level": "Intermediate",
            "courses": 3
        },
        {
            "id": 8,
            "title": "TensorFlow Developer Professional Certificate",
            "authors": [9, 5],
            "level": "Intermediate",
            "courses": 4
        }
    ],
    "authors": [
        {
            "id": 1,
            "name": "Andrew Ng",
            "photo": "headshot-andrew-ng.jpg"
        },
        {
            "id": 2,
            "name": "Kian Katanforoosh",
            "photo": "headshot-kian-katanforoosh.jpg"
        },
        {
            "id": 3,
            "name": "Younes Bensouda Mourri",
            "photo": "headshot-younes-bensouda-mourri.jpg"
        },
        {
            "id": 4,
            "name": "Łukasz Kaiser",
            "photo": "headshot-lukasz-kaiser.jpg"
        },
        {
            "id": 5,
            "name": "Eddy Shyu",
            "photo": "headshot-eddy-shyu.jpg"
        },
        {
            "id": 6,
            "name": "Pranav Rajpurkar",
            "photo": "headshot-pranav-rajpurkar.jpg"
        },
        {
            "id": 7,
            "name": "Amirhossein Kiani",
            "photo": "headshot-amirhossein-kiani.jpeg"
        },
        {
            "id": 8,
            "name": "Bora Uyumazturk",
            "photo": "headshot-bora-uyumazturk.jpeg"
        },
        {
            "id": 9,
            "name": "Laurence Mononey",
            "photo": "headshot-laurence-moroney.jpg"
        },
        {
            "id": 10,
            "name": "Sharon Zhou",
            "photo": "headshot-sharon-zhou.jpg"
        },
        {
            "id": 11,
            "name": "Eda Zhou",
            "photo": "headshot-eda-zhou.jpg"
        },
        {
            "id": 12,
            "name": "Eric Zelikman",
            "photo": "headshot-eric-zelikman.jpg"
        }
    ]
}

Tengo dos archivos js uno es Main.js y otro Course.js

En el Main.js realizo el fetch de ambos (Autores y cursos), desde Main.js le paso a Course.js las props necesarias.

Mi problema viene cuando intento mostrar las url y los distintosnombres de los autores.

Main.js

import React, { useState, useEffect } from 'react';
import Course from "./Course";
import { getAsyncAuthors, getAsyncCourses } from '../services/courses';

function Main() {

    const[course,setCourse] = useState([]);
    const[authors,setAuthors] = useState([]);
    const[loading,setLoading] = useState(false);
    const[cont,setCont] = useState(0);
    
    function loadCourses(){
        setLoading(true);
        getAsyncCourses().then(courses =>{
            setCourse(courses);
            setLoading(false)
        })
    }

    function loadAuthors(){
        getAsyncAuthors().then(authors => {
            setAuthors(authors);
        })
    }

    useEffect(() => {
        async function load(){
            loadCourses();
            loadAuthors();
        }
        load();
        handleAuthorsImage();
    },[])

    function handleFilter(){
        return course.filter(i => i.id <= cont);
    }

    function addCourse(){
        if(cont < course.length){
            if(cont+2 <= course.length){
                setCont(cont+2);
            }else{
                setCont(cont+1);
            }
        }
    }

    function handleAuthorsImage(){
        const auth = course.map(i => i.authors);
        console.log(auth.map(i => i.includes(3) ? "url de authors" : "Bye"));
        //Esta es la funcion en la que intento sacar los nombres de los autores
    }

    return (
        <main className="main">
            <div className="main-container">
                {loading ? "loading..." : handleFilter().map(i => <Course id={i.id} key={i.id} title={i.title} author={i.authors} level={i.level} courses={i.courses} />)}
            </div>
            <div className="main-loading">
                { cont < course.length ? loading ? null : <button onClick={addCourse}>Load more </button> : null}
            </div>
            <h1>{cont}</h1>
        </main>
    )

}

export default Main;

Course.js

import { ReactComponent as CourseIcon } from "../svg/courses.svg";
import { ReactComponent as LevelIcon } from "../svg/level.svg";
import { ReactComponent as AuthorsIcon } from "../svg/authors.svg";

function Course({id, title, level, author, courses}) {

    return (
        <article className="course">
            <div className="course__left">
                <h3 className="course__title">
                    <a href="/" className="course__link">
                        Deep Learning Specialization
                    </a>
                </h3>
                <ul className="course__photos"> //Aqui iria la funcion que realiza un map con todas las imagenes vinculadas con los autores y se eliminaria el tag img estatico 
                    <li className="course__photo">
                        <img src="img/" alt="author" />
                    </li>
                    <li className="course__photo">
                        <img src="img/headshot-kian-katanforoosh.jpg" alt="author" />
                    </li>
                    <li className="course__photo">
                        <img src="img/headshot-younes-bensouda-mourri.jpg" alt="author" />
                    </li>
                </ul>
            </div>
            <div className="course__right">
                <ul className="course__details">
                    <li className="course__detail">
                        <CourseIcon />
                        <div>{courses} courses</div>
                    </li>
                    <li className="course__detail">
                        <LevelIcon />
                        <div>{level}</div>
                    </li>
                    <li className="course__detail">
                        <AuthorsIcon />
                        <div>
                            Andrew Ng, Kian Katanforoosh, Younes Bensouda Mourri
                            //Aqui irian los nombres de los autores
                        </div>
                    </li>
                </ul>
            </div>
        </article>
    )

}

export default Course;

Desde el Main.js he creado la funcion handleAuthorsImage() donde desde ahi hago un map de los authores (las ids) para luego intentar hacer un filtro con courses y que este devuelva las url... Pero no lo consigo, lo he intentado de muchas maneras pero estoy estancado...

He intentado buscar una solucion pero no lo consigo, si alguien puede guiarme o enseñarme como puedo hacerlo lo agradeceria ya que estoy estancado en este punto y no se como solucionarlo.

1 respuesta 1

0

Sugiero recolectar primero todos los datos del curso completo y luego pasárselos como parámetro a cada curso.

Así puedes recolectar la info completa de cada author dentro de cada curso, mira a propiedad authorsInfo:

const courses = [
  {
      "id": 1,
      "title": "AI for Everyone",
      "authors": [1],
      "level": "Introductory",
      "courses": 5
  },
  {
      "id": 2,
      "title": "Deep Learning Specialization",
      "authors": [1, 2, 3],
      "level": "Intermediate",
      "courses": 5
  },
  {
      "id": 3,
      "title": "Natural Language Processing Specialization",
      "authors": [3, 4, 5],
      "level": "Intermediate",
      "courses": 4
  },
  {
      "id": 4,
      "title": "AI for Medicine Specialization",
      "authors": [6, 7, 8, 5],
      "level": "Intermediate",
      "courses": 3
  },
  {
      "id": 5,
      "title": "TensorFlow: Data and Deployment Specialization",
      "authors": [9],
      "level": "Intermediate",
      "courses": 4
  },
  {
      "id": 6,
      "title": "TensorFlow Developer Professional Certificate",
      "authors": [9],
      "level": "Intermediate",
      "courses": 4
  },
  {
      "id": 7,
      "title": "Generative Adversarial Networks (GANs) Specialization",
      "authors": [10, 11, 12],
      "level": "Intermediate",
      "courses": 3
  },
  {
      "id": 8,
      "title": "TensorFlow Developer Professional Certificate",
      "authors": [9, 5],
      "level": "Intermediate",
      "courses": 4
  }
];
const authors = [
  {
      "id": 1,
      "name": "Andrew Ng",
      "photo": "headshot-andrew-ng.jpg"
  },
  {
      "id": 2,
      "name": "Kian Katanforoosh",
      "photo": "headshot-kian-katanforoosh.jpg"
  },
  {
      "id": 3,
      "name": "Younes Bensouda Mourri",
      "photo": "headshot-younes-bensouda-mourri.jpg"
  },
  {
      "id": 4,
      "name": "Łukasz Kaiser",
      "photo": "headshot-lukasz-kaiser.jpg"
  },
  {
      "id": 5,
      "name": "Eddy Shyu",
      "photo": "headshot-eddy-shyu.jpg"
  },
  {
      "id": 6,
      "name": "Pranav Rajpurkar",
      "photo": "headshot-pranav-rajpurkar.jpg"
  },
  {
      "id": 7,
      "name": "Amirhossein Kiani",
      "photo": "headshot-amirhossein-kiani.jpeg"
  },
  {
      "id": 8,
      "name": "Bora Uyumazturk",
      "photo": "headshot-bora-uyumazturk.jpeg"
  },
  {
      "id": 9,
      "name": "Laurence Mononey",
      "photo": "headshot-laurence-moroney.jpg"
  },
  {
      "id": 10,
      "name": "Sharon Zhou",
      "photo": "headshot-sharon-zhou.jpg"
  },
  {
      "id": 11,
      "name": "Eda Zhou",
      "photo": "headshot-eda-zhou.jpg"
  },
  {
      "id": 12,
      "name": "Eric Zelikman",
      "photo": "headshot-eric-zelikman.jpg"
  }
];

const authorInfoById = authors.reduce((accum, value) => {
   accum[value.id] = value;
   return accum;
}, {})

const fullCoursesInfo = courses.map(course => {
   const authorsInfo = course.authors.map(authorId => authorInfoById[authorId]);
   return { ...course, authorsInfo }
});

console.dir(fullCoursesInfo, {depth: null});

Y ya teniendo la info completa te queda más fácil de renderizar dentro del componente.

Saludos.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.