kopeet34
kopeet34

Reputation: 1

React - 'state' is assigned a value but never used no-unused-vars

I have this code and I get error message:

src/App.js Line 5:11: 'state' is assigned a value but never used no-unused-vars.

What I do wrong? Thanks for help!

import Some from './Some/Some';

const App = () => {
    const state = ({
        persons: [
            {name: 'Connor', text: 'This is first.'},
            {name: 'Megan', text: 'This is second.'},
            {name: 'Jcob', text: 'This is third.'}
        ]
    }
);
    return (
        <div className="App">
            <h1>Hi, React!</h1>
            <Some name={this.state.persons[0].name} text={this.state.persons[0].text} />
            <Some name={this.state.persons[1].name} text={this.state.persons[1].text} />
            <Some name={this.state.persons[2].name} text={this.state.persons[2].text} />
        </div>
    );
}

export default App;

Upvotes: 0

Views: 3131

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370709

You should only refer to this.state inside class components. Inside functional components, there is no this, only local variables.

While you could change to:

<Some name={state.persons[0].name} text={state.persons[0].text} />

Using .map would make more sense, as would declaring only a persons array without the surrounding object:

const App = () => {
    const persons = [
        {name: 'Connor', text: 'This is first.'},
        {name: 'Megan', text: 'This is second.'},
        {name: 'Jcob', text: 'This is third.'}
    ];
    return (
        <div className="App">
            <h1>Hi, React!</h1>
            {
                persons.map(p => <Some name={p.name} text={p.text} />)
            }
        </div>
    );
}

If you need actual state in a functional component, you should use useState, eg:

const [persons, setPersons] = useState([
    {name: 'Connor', text: 'This is first.'},
    {name: 'Megan', text: 'This is second.'},
    {name: 'Jcob', text: 'This is third.'}
]);

(but the current component doesn't look to be doing anything stateful, at least not yet)

Upvotes: 3

Related Questions