No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Curso de Next.js 2018

Curso de Next.js 2018

Roberto González

Roberto González

Recibiendo Parámetros

8/23
Recursos

En esta clase vamos a ver cómo hacer una de las cosas más cruciales que tenemos en cualquier aplicación, que es recibir parámetros sobre una página.

Aportes 14

Preguntas 4

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

Yo escribí channel.jsx de esta forma me gusta mas:

export default class extends React.Component {
  static async getInitialProps({ query }) {
    let reqChannel = await this.getChannel(query.id);
    let reqAudioClips = await this.getAudioClipsChannel(query.id);
    let reqSeries = await this.getSeries(query.id);
    return {
      channel: reqChannel.channel,
      audio_clips: reqAudioClips,
      series: reqSeries
    };
  }

  static async getChannel(idChannel) {
    let req = await fetch(`https://api.audioboom.com/channels/${idChannel}`);
    let {
      body: { channel }
    } = await req.json();
    return { channel };
  }

  static async getAudioClipsChannel(idChannel) {
    let req = await fetch(
      `https://api.audioboom.com/channels/${idChannel}/audio_clips`
    );
    let dataAudios = await req.json();
    return dataAudios.body.audio_clips;
  }

  static async getSeries(idChannel) {
    let req = await fetch(
      `https://api.audioboom.com/channels/${idChannel}/child_channels`
    );
    let dataSeries = await req.json();
    return dataSeries.body.channels;
  }

  render() {
    const { channel, audio_clips, series } = this.props;
    console.log(this.props);

    return (
      <div>
        <header>Podcasts</header>
        <h1>{channel.title}</h1>

        <h2>Series</h2>
        {series.map(serie => (
          <div>{serie.title}</div>
        ))}

        <h2>Podcast</h2>
        {audio_clips.map(clip => (
          <div>{clip.title}</div>
        ))}
        <style jsx>
          {`
            header {
              color: #fff;
              background: #8756ca;
              padding: 15px;
              text-align: center;
            }
            .channels {
              display: grid;
              grid-gap: 15px;
              padding: 15px;
              grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
            }
            a.channel {
              display: block;
              margin-bottom: 0.5em;
              color: #333;
              text-decoration: none;
            }
            .channel img {
              border-radius: 3px;
              box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.15);
              width: 100%;
            }
            h1 {
              font-weight: 600;
              padding: 15px;
            }
            h2 {
              padding: 5px;
              font-size: 0.9em;
              font-weight: 600;
              margin: 0;
              text-align: center;
            }
          `}
        </style>
        <style jsx global>
          {`
            body {
              margin: 0;
              font-family: system-ui;
              background: white;
            }
          `}
        </style>
      </div>
    );
  }
}

Por qué desde channel.js no hace falta importar “isomorphic-fetch”? Noto que también estamos usando fetch() en este archivo.

Increible como esta llendo el curso !!!

como hago para ver el api de esa manera. que plugging usa? yo abro esa url y veo la data pero no me aparece de manera comestible.??

Hola, por qué en esta página de Channel.js funciona el fetch si no se está importando el isomorphic?

Si a la fecha a alguien se le presenta este warning en consola:

Simplemente deben agregar un key a cada <div/> que nos devuelve la lista:

   <h2>Series</h2>
    {series.map(seri => (
      <div key={seri.id}>{seri.title}</div>
    ))}

   <h2>Ultimos podcasts</h2>
    {audioClips.map(clip => (
      <div>{clip.title}</div>
    ))}

Implementacion de channel como componente funcional:

const Channel = ({ channel, audioClips, series }) => {
    return (
        <div>
            <header>Podcast</header>

            <h1>{channel.title}</h1>

            <h2>Ultimos Podcasts</h2>
            {
                audioClips.map((clip, key) => (
                    <div key={key}>{clip.title}</div>
                ))
            }
            <h2>Series</h2>
            {
                series.map((serie, key) => (
                    <div key={key}>{serie.title}</div>
                ))
            }
            <style jsx>
                {
                    `
                    header{
                        color: #fff;
                        background: #8756ca;
                        padding: 15px;
                        text-align: center;
                    }

                    h1{
                        padding: 3px;
                        text-align:center;
                        font-size: 16px
                    }
                    `
                }
            </style>

            <style jsx global>
                {
                    `
                body{
                    background: white;
                    margin:0;
                    font-family: system-ui
                }
                `
                }

            </style>
        </div>
    )
}

Channel.getInitialProps = async ({ query }) => {
    let idChannel = query.id;

    let reqChannel = await fetch(`https://api.audioboom.com/channels/${idChannel}`);
    let dataChannel = await reqChannel.json();
    let channel = dataChannel.body.channel;

    let reqAudio = await fetch(`https://api.audioboom.com/channels/${idChannel}/audio_clips`);
    let dataAudio = await reqAudio.json();
    let audioClips = dataAudio.body.audio_clips;

    let reqSeries = await fetch(`https://api.audioboom.com/channels/${idChannel}/child_channels`);
    let dataSeries = await reqSeries.json();
    let series = dataSeries.body.channels;
    return { channel, audioClips, series };
}

export default Channel```

Si se reinicia el servidor y entramos directo a la pagina de channel/:id entonces bota el error de que fetch no está definido. Habrá que definirlo siempre en nuestras paginas.

Por que no crear un los componentes reutilizables como el Header

como puedo ver los datos del api en el navegador de forma digerible para ver la estructura? si abro la url me trae los datos pero sin un formato ordenado??

Este es mi JSX Style para tener la misma vista ue mostro al principio.

header {
                        color: #fff;
                        background: #8756ca;
                        padding: 15px;
                        text-align: center;
                    }

                    .channels {
                        display: grid;
                        grid-gap: 15px;
                        padding: 15px;
                        grid-template-columns: repeat(
                            auto-fill,
                            minmax(160px, 1fr)
                        );
                        color: black;
                    }

                    .channel {
                        display: flex;
                        border-radius: 4px;
                        box-shadow: 0px 3px 4px rgba(0, 0, 0, 0.15);
                        text-decoration: none;
                        overflow: hidden;
                        transition: all ease 0.2s;
                    }

                    .channel img {
                        margin: auto;
                        width: 100%;
                    }

                    .channel:hover {
                        transform: translateY(-0.5em);
                    }

                    h2 {
                        padding: 5px;
                        font-size: 12px;
                        font-weight: 600;
                        margin: 0.5em 0 0 0;
                        text-align: center;
                    }

Además de Next, me gusta aprender las diferentes sintaxis:
async getMethod(parametro) { let query = parametro.query }
Es exactamente igual que tener:
async getMethod([ query }) { }

Hola, tengo otra consulta relacionada con nextJS. En este ejemplo channel y audio_clips

  let channel = fetch(`https://api.audioboom.com/channels/${query.id}`)
    .then(response => response.json())
    .then(response => renameBodytoChannel(response.body));
  let audio_clips = fetch(
    `https://api.audioboom.com/channels/${query.id}/audio_clips`
  )
    .then(response => response.json())
    .then(response => renameBodytoAudio_clips(response.body));
  return { channel, audio_clips };
};```

me llegan undefined las props. Porq seran?

antes me funcionaba porque devolvia todo de la siguiente forma
```Channel.getInitialProps = ({ query }) =>
  fetch(`https://api.audioboom.com/channels/${query.id}`)
    .then(response => response.json())
    .then(response => renameBodytoChannel(response.body));

en este caso channel devolvia valores, pero al agregar audio_clips no me funciona nada 😞

No se si soy el unico con este error por asi decirlo. Pero el Api se ha actualizado por que no existen child channels para todos los podcast solo encontre para uno.