1

When I'm going to a new route (/category/name-of-category) that renders my Category component, the array I'm trying console.log is empty. BUT when I refresh the page, the array gets data? What am I doing wrong? Im not so good at explaining, so I created a video for it.

Video of the problem:

enter image description here

This is my Category Component where I console.log the array:

import React, { Component } from 'react'
import PodcastList from './PodcastList'
import { podcastCategories } from './api'

export default class Category extends Component {

  render() {
    const categoryId = this.props.match.params.categoryId
    const categoryName = this.props.match.params.categoryName
    const currentCategory = podcastCategories.filter(category => category.slug === categoryName)
    console.log(currentCategory)
     return (
      <div className='container'>
        <PodcastList key={categoryId} categoryId={categoryId} name={categoryName} amount='100' />
      </div>
    )
  }
}

My child component:

import React, { Component } from 'react'
import PodcastItem from './PodcastItem'
import { Link } from 'react-router-dom'
import slugify from 'slugify'
import { fetchPodcastCategory } from './api'

export default class PodcastList extends Component {

  state = {
    podcasts: [],
    loading: true,
  }

  async componentDidMount () {
    const categoryId = this.props.categoryId
    const totalAmount = this.props.amount
    const podcasts = await fetchPodcastCategory(categoryId, totalAmount);
      this.setState({
        podcasts,
        loading: false,
      })
  }

  render() {
    const podcasts = this.state.podcasts
    const { name, amount, categoryId } = this.props

    let description;
            if (amount === '100') {
              description = (
                        <p>Populäraste poddarna inom {name}</p>
              )
            } else {
              description = (
                <p>Topp {amount} poddar inom {name} -&nbsp;
                <Link to={`/kategori/${slugify(name.toLowerCase())} `}>
                 Visa Topp 100
              </Link>
            </p>
              )
            }

      return (
         <div className='row category-list'>
            <div className='col-md-12'>
            <h2>{name}</h2>
            { description }
            {podcasts.map((pod) => {
                const podId = pod.id.attributes['im:id']
                const podImage300 = pod['im:image'][0].label.replace('55x55bb-85', '300x300bb-75')
                const podImage600 = pod['im:image'][1].label.replace('60x60bb-85', '600x600bb-75')
                const podImage900 = pod['im:image'][2].label.replace('170x170bb-85', '900x900bb-75')
                const podImages = { podImage300, podImage600, podImage900 }
                const podName = pod['im:name'].label
                return (
                    <div key={podId} className='pod-box'>
                    <PodcastItem id={podId} image={podImages} name={podName}/>
                    </div>
                )
            })}
            </div>
        </div>
      )
    }
}

My Api.js:

import Feed from 'feed-to-json-promise'

export async function fetchPodcastCategory (categoryId, amount) {
  const response = await fetch(`/api/podcast/${categoryId}/${amount}`);
  const podcasts = await response.json();

  return podcasts.feed.entry;
}

export async function fetchPodcast (podId) {
  const response = await fetch(`/api/podcast/${podId}`);
  const podcasts = await response.json();

  return podcasts.results;
}

export async function fetchPodcastEpisodes (feedUrl) {
  const feed = new Feed();
  const episodes = await feed.load(`/api/podcast/episodes?feedurl=${feedUrl}`)
  return episodes;
}


export const podcastCategories = [
  { id: '1301', name: 'Konst och kultur', slug: 'konst-och-kultur'},
  { id: '1303', name: 'Komedi och humor', slug: 'komedi-och-humor' },
  { id: '1304', name: 'Utbildning', slug: 'utbildning' },
  { id: '1305', name: 'Barn och familj', slug: 'barn-och-familj' },
  { id: '1307', name: 'Hälsa', slug: 'halsa' },
  { id: '1309', name: 'TV och Film', slug: 'tv-och-film' },
  { id: '1310', name: 'Musik', slug: 'musik' },
  { id: '1311', name: 'Nyheter och politik', slug: 'nyheter-och-politik' },
  { id: '1314', name: 'Religion och andlighet', slug: 'religion-och-andlighet' },
  { id: '1315', name: 'Vetenskap och medicin', slug: 'vetenskap-och-medicin' },
  { id: '1316', name: 'Sport och fritid', slug: 'sport-och-fritid' },
  { id: '1318', name: 'Tenik', slug: 'teknik' },
  { id: '1321', name: 'Affärer', slug: 'affarer' },
  { id: '1323', name: 'Spel och hobby', slug: 'spel-och-hobby' },
  { id: '1324', name: 'Samhälle och kultur', slug: 'samhalle-och-kultur' },
  { id: '1325', name: 'Myndighet och organisation', slug: 'myndighet-och-organisation' },
]

when I console.log: podcastCategories & categoryName enter image description here

Jonas Alvarson
  • 411
  • 2
  • 6
  • 20

4 Answers4

0

Can you add the .api files that you're bringing in?

This is a guess... since I can't see the full picture but it seems like something isn't coming in properly from the .api file.

Can you console.log(categoryName) and console.log(podcastCategories) before console logging currentCategory? Also is there a parent for Category? If so, please post the code for that.

Sorry. I would comment rather than answer but I don't have enough points yet. :(

Holly E
  • 563
  • 1
  • 5
  • 15
0

I'd check categoryId because <PodcastList key={categoryId} with the same key will be treated as already mounted and only updated with new props - componentDidMount won't be called/fired.

xadm
  • 8,219
  • 3
  • 14
  • 25
0

I solved it! I really tought it was something fuzzy going on. So I tried to to do this in the terminal:

  1. killall -9 node
  2. ps ax

and after that restart my node.js server. And for some reason now it works.

Jonas Alvarson
  • 411
  • 2
  • 6
  • 20
0

Jonas, your code works now because category.slug = categoryName is an assignment, not a check of truth. It will return the truthiness of the value assigned to category.slug, i.e. categoryName. So seems like categoryName is defined, but is not strictly equal to category.slug. Holly E asked a good question--can you show what categoryName shows in the console? And what about podcastCategories? If you add that to your code above, we should be able to see why the strict equality is not doing what is expected.

ZebGir
  • 123
  • 1
  • 7
  • Your right.. my bad. I have updated the question now with what I get when I console.log categoryName & podcastCategories @ZebGir – Jonas Alvarson Oct 02 '18 at 19:12