4156
4156

Reputation: 400

Find() only showing first array in an object

I'm having a trouble with my Redux/React project in which I call an API and look for a specific ID based on what is in a useParams. I believe I've limited the problem down to my return statement return data.hero.find(hero => <Hero key={hero.id} hero={hero} />)

I'm not sure if that is how I should be writing it.

edit: I have seemed to fix the issue of the objects not being valid, however now my find() function only shows the first hero in the array, unsure of how to fix that problem without creating a new thread HeroPage

import React, {useEffect} from 'react'
import { useSelector } from 'react-redux'

import { fetchHero } from '../actions/heroAction'
import { Hero } from '../components/Hero'
import {useParams} from "react-router";

const HeroPage = () => {
    const data = useSelector(state => state.hero);
    const {heroId} = useParams()
    useEffect(() => {
        (fetchHero({heroId}))
    }, [heroId])


    let content;

    if (data.loading) content = <p>Loading posts...</p>;
    else if (data.hasErrors) content = <p>Unable to display posts</p>
    else {
        // Fill in actual check here
        const hero = data.hero.find(hero => hero.id === +heroId ? null : 'Could not find')
        // May not exist in the array
        if (hero) {
            content = <Hero key={hero.id} hero={hero}/>
        }
    }


    return (
        <section>
            <h1>Hero</h1>
            {content}
        </section>
    )

}



Upvotes: 0

Views: 52

Answers (1)

Brian McCutchon
Brian McCutchon

Reputation: 8584

Find only takes a Boolean function; don't try to do rendering in it. You should use find to get a hero, then do rendering after:

const hero = data.hero.find(hero => hero.id === +heroId)
if (hero) {
  content = <Hero key={hero.id} hero={hero} />
}

Upvotes: 1

Related Questions