Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js :You called `setState` with a callback that isn't callable

This is my piece of code, which works correctly (adds records), but throws an error after addition:

Uncaught Error: Invariant Violation: enqueueCallback(...): You called setProps, replaceProps, setState, replaceState, or forceUpdate with a callback that isn't callable.

handleSubmit: function(e) {
    e.preventDefault();
    return $.post('', {page: this.state},
      function(data) {
        this.props.handleNewPage(data);
        return this.setState(this.getInitialState(), 'JSON');
      }.bind(this)
    );
  }

There are no routes for now. Can someone help me to solve this?

like image 490
Fleeck Avatar asked Jul 14 '15 07:07

Fleeck


People also ask

How do you use callback in setState in React?

The use case for setState callback is quite clear. You use it when you want a function to run after a SPECIFIC state has been updated. If you put this function in render() instead, it will run every time ANY state is updated, which is probably not what you want. This will also make your code less readable and logical.

Does setState take a callback?

The setState function takes an optional callback parameter that can be used to make updates after the state is changed. This function will get called once the state has been updated, and the callback will receive the updated value of the state.

Can we have a callback function which will be invoked when setState has finished?

setState allows a second parameter to be passed to it as a callback. The callback function is invoked whenever the state of the function gets updated. But, this callback mechanism does not exist with functional components. The callback function would not be invoked in this case, and it would throw a warning instead.

How do you add a callback on setState?

setState Callback in a Class Component import React, { Component } from 'react'; class App extends Component { constructor(props) { super(props); this. state = { age: 0, }; } // this. checkAge is passed as the callback to setState updateAge = (value) => { this. setState({ age: value}, this.


1 Answers

The second (optional) parameter to setState is a callback function, not a string. You can pass a function that will be executed once the operation is completed.

like image 164
Madara's Ghost Avatar answered Sep 21 '22 02:09

Madara's Ghost