12- Lifting the State Up

So I’m following Moshes instructions and I can tell his React Course is out of date.

I have a reference error that says “state is not defined”.
state

I have how ever noticed my coding structure on my App.js is slightly different then what Mosh has. For example I have “function App()” where as Mosh has “class App extends Component”. That’s how it came when I created the counter app.

How exactly do I change this to make it work?

Here’s my code:

import React, { Component } from ‘react’;

import NavBar from ‘./components/navbar’;

import Counters from “./components/counters”;

import ‘./App.css’;

function App() {

state = {

counters: [

    { id: 1, value: 4 },

    { id: 2, value: 0 },

    { id: 3, value: 0 },

    { id: 4, value: 0 }

]

};

handleIncrement = counter => {

 //console.log(counter);

 const counters = [...this.state.counters];

 const index = counters.indexOf(counter);

 counters[index] = {...counter};

 counters[index].value++;

 //console.log(this.state.counters[index]);

 this.setState({ counters });

};

handleReset = () => {

const counters = this.state.counters.map(c => {

    c.value = 0;

    return c;

});

this.setState({ counters });

};

handleDelete = (counterId) => {

//console.log("Event Handler Called", counterId);

const counters = this.state.counters.filter(c => c.id !== counterId);

this.setState({ counters });

};

//render () {

return (

  <React.Fragment>

  <NavBar />

  <main className="container">

    <Counters 

    counters={this.state.counters}

    onReset={this.handleReset} 

    onIncrement={this.handleIncrement}

    onDelete={this.handleDelete}

    />

  </main>

  </React.Fragment>

);

//}

}

export default App;

1 Like

Dear pfabbi,

change your code to the following:

class Counter extends Component {
state = {
counters: [
{ id: 1, value: 4 },
{ id: 2, value: 0 }
]
}
render() {
return (
null
);
}
}

You receive an error because you are using a stateless functional component!!!
(Cheers)

Dr Press,

I have the same issue described by pfabbi but need more help with your solution. Are you saying that the state should be defined in counter.jsx file and not app.js?

@Debo Try changing your

function App() {

to

class App extends Component {

This specific part of the course is outdated, but Mosh will explain this later in the course, bring everything up to date, and you’ll be able to understand why this change is necessary. For now I suggest just changing this, not worrying about why, and then following along with the course.

3 Likes