Home > Net >  React: TypeError for split : Cannot read properties of undefined (reading 'split')
React: TypeError for split : Cannot read properties of undefined (reading 'split')

Time:10-12

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 
    });
}

CodePudding user response:

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
       />

     </>
   )
}

}


CodePudding user response:

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.

  • Related