Unhandled Rejection (Typeerror): this.setState.list is Undefined

Asked

Viewed 122 times

-2

I’m doing a project of the kind CRUD with the React and in compiling it appeared:

"Unhandled Rejection (TypeError): this.setState.list is undefined"

export default class UserCrud extends Component {

    state = { ...initialState}

    clear ()  {
        this.setState({user: initialState.user})
    }

    save () {
        const user = this.state.user
        const method = user.id ? 'put' : 'post'
        const url = user.id ? `${baseUrl}/${user.id}` : baseUrl //outro erro
        axios[method] (url, user)
        .then(resp => {
            const list = this.getUpdateList(resp.data)
            this.setState({user: initialState.user, list})
        })
        
    }

    getUpdateList  (user) { // onde está o erro
        const list = this.setState.list.filter(u => u.id !== user.id)
        list.unshift(user)
        return list
    }

    updateField (event)  {
        const user = { ...this.state.user}
        user[event.target.name] = event.target.value
        this.setState({user})
    }
  • initialState What is that? There’s no such thing: const list = this.setState.list.filter(u => u.id !== user.id) and I think pure supposition that is const list = this.state.list.filter(u => u.id !== user.id)

1 answer

0

To answer this question we need to understand what the state and setState of React are.

State

It is a property of the class instance of its component, the React doc defines state to be:

The state contains data specific to this component that can change over time. The state is user-defined and must be a Javascript object.

If any value is not used for rendering or for control of data flow (for example, a timer ID), you don’t need to put in state. Such values can be defined as fields in the instance of component.

And one important thing that documentation talks about is:

Never change this.state directly, because calling setState() after the mutation can replace the mutation performed. Treat this.state as if it is immutable.

That is, the state is like a "reactive variable" that you have, which contains an object, in which you can store values that when modified, will have effects on the interface.

Setstate

As the state documentation itself warns, you should never make a direct assignment to the state with this.state = {chave: valor} for example, to change the value of a state you should always use the setState function.

The problem described

In this line:

const list = this.setState.list.filter(u => u.id !== user.id)

What you apparently want is the "list" value that is within the state, not the setState function, which can be corrected by replacing this line with:

const list = this.state.list.filter(u => u.id !== user.id)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.