1

I am trying to fetch data via apı and I kinda did it. However, I have problem wwith split. I tried everything but I got still this error. How can I Achive that?

edit: I installed this $npm add react-split and import it like so : import Split from 'react-split'. This is the usage of it in a code:

import React, {Component} from "react";
import { Link } from "react-router-dom";

 class PokemonDetail extends Component {
    constructor(props) {
    super(props);
    this.state = {
    name: '',
    imgUrl: '',
    pokemonIndex: '',
    
  };
}
componentDidMount() {
    const {name, url} = this.props;
    const pokemonIndex = url.split('/')[url.split('/').length - 2];
    const imageUrl = `https://github.com/PokeAPI/sprites/blob/master/sprites/pokemon/${pokemonIndex}.png?raw=true`;
    
    this.setState ({
       name: name,
       imageUrl: imageUrl,
       pokemonIndex: pokemonIndex 
    });
}
7
  • whats the error? Commented Oct 11, 2021 at 20:52
  • TypeError: Cannot read properties of undefined (reading 'split') Commented Oct 11, 2021 at 20:53
  • that means that the variable url is undefined Commented Oct 11, 2021 at 20:55
  • didn' I define it like so: const {name, url} = this.props; Commented Oct 11, 2021 at 20:58
  • if you console.log this.props you will see that there is no url Commented Oct 11, 2021 at 21:00

2 Answers 2

5

I solved the problem by inserting question mark before split. I do not know the reason but it worked.

        const pokemonIndex = url?.split('/')[url?.split('/').length - 2];

Thanks all who responded my post.

Sign up to request clarification or add additional context in comments.

1 Comment

The ? checks if the object is undefined. If url is undefined, then you cannot access the method split() on it. The ? asks, "Is url not undefined? if so, then .split() ... "
0

Please make sure the parent component that call this PokemonDetail send the props with the same name.

Like this

class Pockemon extend Component {

render(){
   return (
     <>
       <PokemonDetail
          name='Pockemon name' // this line 
          url='the url' // and this line
       />

     </>
   )
}

}


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.