React TypeError: Cannot read property 'replace' of undefined

cannot read property of undefined react state
cannot read property of undefined react function
cannot read property 'state' of undefined angular
typeerror: cannot read property of undefined
typeerror: cannot read property 'value' of undefined react
react cannot read property 'map' of undefined
react cannot read property of null
cannot read property 'email' of undefined react

I cannot figure out why I am getting an error for a replace function inside the Render function of my component.

TypeError: Cannot read property 'replace' of undefined

I am simply trying to replace the string value from services.serviceImage and replace the string like "react-site/public/","" just like you would normally do on any string, I made some tests and I can confirm the value returned is a string and I made some other string replaces and it worked but in this case something is not working...why?

I have already tried as a regex method with no luck:

imgUrl = imgUrl.replace("/react\-site\/public/g", "");

For some reason, my node server won't accept a replace method for the doc.serviceImage response either!!!

What am I doing wrong here...?

My complete code:

import React, {Component} from 'react';
import axios from 'axios';
//import { Link } from "react-router-dom";
import './catalogue.scss';

class ServicesPage extends Component {
  state = {
    services: [],
    loading: false
  }
  componentDidMount(){

    this.setState({
      loading: true
    });

    axios.get('/services')
    .then(response => {
      console.log(response);
      this.setState({
        services: response.data.services,
        loading: false
      });
    })
    .catch( error => {
      console.log(error);
    });
    document.title = "Pain Relief and Massage Services - LA Therapy";
  }//componentDidMount

  replaceStr(str, newStr) {
   return  str = str.replace(str, newStr);
  }

  render(){

    let pageRender; 
    if(this.state.loading){
     pageRender =  <div className="pageLoader">Loading... <img src="./images/ui/spinner.svg"/></div>
    }else{
      {this.state.services.map(services => {
        let backgroundUrl = {};
        let imgUrl = services.serviceImage;

        imgUrl = imgUrl.replace("/react\-site\/public/g", ""); //this string replace is not working

        console.log(imgUrl);


        if (services.serviceImage) {

           backgroundUrl = {
            backgroundImage: `url(${imgUrl})`,
            backgroundSize: 'cover'  
          };

        }else{
         backgroundUrl = {
            backgroundImage: 'url(./images/ui/add-image-wide.png)',
            backgroundSize: 'cover'  
          };

          pageRender =  <div className="columns white-bg">
          <div className="grid-x">
          {this.state.services.map(services =>

            <div key={services._id} className="cell large-6 medium-12 small-12 end padding-all-3x">
            <div className="catalogue-medium gray_2-border white-bg margin-distributed round-small" style={backgroundUrl}>
              <div className="dark-overlay"></div>
              <img src="./uploads/services/1538735070981-1538653957308-back-massage.jpg"/>
              <div className="tittle-bottom">{services.name} </div>
            </div>
            </div> 
            )}
          </div>
        </div>


        }

        })
      }
    }

    return(
      <div>
        {pageRender}
      </div>
    );
  }
}

export default ServicesPage;

You look to see if the property is valid AFTER you use it

let imgUrl = services.serviceImage;  <-- read it
imgUrl = imgUrl.replace(...)  <-- where the error occurs
if (services.serviceImage) {  <-- is truthy

So move the logic inside the check

let imgUrl = services.serviceImage; 
if (services.serviceImage) {  
  imgUrl = imgUrl.replace(...)

or set it to an empty string if you some reason need imgUrl outside of the if

let imgUrl = services.serviceImage || '';
imgUrl = imgUrl.replace(...)

[Solution] React, [Solution] React - TypeError: Cannot Read Property of Undefined. This is a common error that all React developers run into at some point. The most common​  Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. React : TypeError: Cannot read property 'Item' of

You might check the this.state.services first, before actually rendering them

 { this.state.services.length > 0 && this.state.services.map(services => {
        let backgroundUrl = {};
        let imgUrl = services.serviceImage;

        imgUrl = imgUrl.replace("/react\-site\/public/g", ""); //this string replace is not working

        console.log(imgUrl);

TypeError: Cannot read property 'state' of undefined with create , TypeError: Cannot read property 'state' of undefined with create-react-class #​12096. Closed. dallashuggins opened this issue on Jan 25, 2018 · 10 comments. getAPIData() { fetchFactory('/url', 'GET') .then(function (data) { this.displayAPIData(data); }) } // Uncaught (in promise) TypeError: Cannot read property of undefined Reason of the issue The scope of the special object this limited to the callback function, it does not have displayAPIData method defined.

Maybe the imageUrl is undefined initially, try for a string check whether the variable is a string. The code goes like:

imgUrl = typeof imgUrl === 'string' ? imgUrl.replace("/react\-site\/public/g", "") : '';

TypeError: Cannot read property state of undefined, term). class SearchBar extends React.Component { state = { term: '' }; onFormSubmit(event) { event. Uncaught TypeError: Cannot read property 'map' of undefined at {Component}.render in ReactJs 0 history.push() and props.location.state cause “Cannot read property 'state' of undefined”

Put you imgUrl.replace(...) inside the if (services.serviceImage) statement. In some cases services.serviceImage has an undefined value and you are getting error cuz of that.

...

if (services.serviceImage) {

let backgroundUrl = {};
let imgUrl = services.serviceImage;

imgUrl = imgUrl.replace("/react\-site\/public/g", ""); //this string replace is not working

console.log(imgUrl);

backgroundUrl = {
   backgroundImage: `url(${imgUrl})`,
   backgroundSize: 'cover'  
};

}

...

You have to avoid changing state with an undefined value. you are getting and undefined value and setting it to the state. your state will get changed and renders over an undefined value. First of all, you have to check if services.serviceImage has a value then you set the value to the state. Secondly, on you render wrap your if statement over your all code to make sure you will run your code over a true value.

React/Redux Render Error: 'TypeError: Cannot read property , Trying to access a property of null throws 'Uncaught TypeError: Cannot read property [propertyName] of null'. Instead of the status value remaining as 'Guest'  Dismiss Join GitHub today. GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.

React.js "Cannot read property" issue., React.js "Cannot read property" issue. Ok, I keep getting the "× TypeError: Cannot read property 'props' of undefined" in the browser. I'll include  Uncaught TypeError: Cannot read property 'setState' of undefined. even after binding delta in the constructor. class Counter extends React.Component { constructor(props) { super(props); this.state = { count : 1 }; this.delta.bind(this); } delta() { this.setState( { count : this.state.count++ }); } render() { return ( <div> <h1> {this.state.count}</h1> <button onClick= {this.delta}>+</button> </div> ); } }

React, If you are a react developer, there is a good chance that you faced this error couple of times: TypeError: Cannot read property 'map' of  Hello, After updating to React 15.0.1, we are getting the following error: Uncaught TypeError: Cannot read property 'addEventListener' of null

ReactJS, Hi folks, I have an issue with this code: render() { const { disruptions } = this.state; disruptions.map(disruption => { return ( <div> {disruption.title}  TypeError: Cannot read property 'updater' of undefined To reproduce import React, {Component} from 'react'; import logo from './logo.svg'; import Do you want to request a feature or report a bug? Bug report What is the current behavior?

Comments
  • The error tells you that imgUrl is undefined before you call replace() on it. You need to add console.log() calls to find out why. I suggest checking this.state.services to be sure each element has serviceImage. For more tips on debugging your code read ericlippert.com/2014/03/05/how-to-debug-small-programs.
  • Could you please add the string value of services.serviceImage where you are console.log(imgUrl)?
  • The object returns 9 undefined and 3 with value could it be the problem?