logo
down
shadow

React not updating state with setState correctly inside promises


React not updating state with setState correctly inside promises

Content Index :

React not updating state with setState correctly inside promises
Tag : javascript , By : Steve Jones
Date : January 12 2021, 01:40 AM

will help you It's hard to tell because the code is incomplete, but I see two problems (assuming the missing ] is just a typo in the question):
You're not spreading out response.data.items in the setData call. You're using existing state to set new state, but not doing it with the callback version of the state setter. The documentation is inconsistent about this, but you should use the callback version when setting state based on existing state unless you know you only update state in certain specific event handlers (like click) that React specifically handles flushing updates for.
const App = props => {
    const [data, setData] = useState({ ... });
    // ...
    function handleLoadMore(uri) {
        // *** Use callback
        setData(current => ({...current, isLoadingMore: true}));
        axios
            .get(uri)
            .then(response => {
                // *** Use callback, spread response.data.items
                setData(current => ({
                    ...current,
                    items: [...current.items, ...response.data.items]
                }));
            })
            .catch(error => {
                // *** Use callback
                setData(current => ({...current, error: 'An error occured'}));
            })
            .finally(() => {
                // *** Use callback
                setData(current => ({...current, isLoadingMore: false}));
            });
    }
}
const App = props => {
    const [data, setData] = useState({ ... });
    // ...
    function handleLoadMore(uri) {
        setData(current => ({...current, isLoadingMore: true}));
        axios
            .get(uri)
            .then(response => {
                setData(current => ({
                    ...current,
                    items: [...current.items, ...response.data.items],
                    isLoadingMore: false // ***
                }));
            })
            .catch(error => {
                setData(current => ({
                    ...current,
                    error: 'An error occured',
                    isLoadingMore: false // ***
                }));
            });
    }
}
const App = props => {
    const [items, setItems] = useState([]);
    const [loadingMore, setLoadingMore] = useState(false);
    const [error, setError] = useState("");
    // ...
    function handleLoadMore(uri) {
        setLoadingMore(true);
        axios
            .get(uri)
            .then(response => {
                setItems(currentItems => [...currentItems, ...response.data.items]);
            })
            .catch(error => {
                setError('An error occured');
            })
            .finally(() => {
                setLoadingMore(false);
            });
    }
    // ...
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

React setState not updating state


Tag : javascript , By : Thx1138.6
Date : March 29 2020, 07:55 AM
To fix the issue you can do setState() is usually asynchronous, which means that at the time you console.log the state, it's not updated yet. Try putting the log in the callback of the setState() method. It is executed after the state change is complete:
this.setState({ dealersOverallTotal: total }, () => {
  console.log(this.state.dealersOverallTotal, 'dealersOverallTotal1');
}); 

React Native: Updating state in onLayout gives "Warning: setState(...): Cannot update during an existing state tran


Tag : react-native , By : Terrence Poon
Date : March 29 2020, 07:55 AM
To fix the issue you can do We got around this by using the measure function, you will have to wait until the scene is fully complete before measuring to prevent incorrect values (i.e. in componentDidMount/componentDidUpdate). Here's an example:
  measureComponent = () => {
    if (this.refs.exampleRef) {
      this.refs.exampleRef.measure(this._logLargestSize);
    }
  }

  _logLargestSize = (ox, oy, width, height, px, py) => {
    if (height > this.state.measureState) {
      this.setState({measureState:height});
    }
  }

render() {
  return (
    <View ref = 'exampleRef' style = {{minHeight:  this.props.minFeedbackSize}}/>
  );
}

React state updating without setState


Tag : reactjs , By : Pavel K.
Date : March 29 2020, 07:55 AM
Does that help I am trying to add items to a cart and I have set a condition to setState only when the quantity items.quantity in stock is greater than or equal to the quantity being added items.qty but it seems to ignore the condition and even the setState call. , If Items is an array, you could do
let newItems = this.state.items.slice();
let array1 = [{foo: 'bar'}];
let array2 = array1.slice();
array2.push({foo: 'new'});

// array 1 not affected
console.log(array1);

array1[0].foo = 'changed';
// array2 affected
console.log(array2);

state not updating with setState react


Tag : reactjs , By : Patastroph
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I think you would want to do this.setState(obj) so that they dynamic key gets merged in to the state.

React setState not updating correctly


Tag : reactjs , By : James Lupiani
Date : March 29 2020, 07:55 AM
Hope this helps Check out the docs. State updates are asynchronous. Make sure you account for this by using a callback with setState if later lines of code will rely on the new state.
the signature of this.setState is this.setState(update, callback), so you can write your code like this:
addBudgetItem (item, amount, category) {
  let newIncomeTotal = this.state.totalIncome + parseInt(amount);
    this.setState({
      incomeItems: [...this.state.incomeItems, {item: item, amount: amount, category: category}],
      totalIncome: newIncomeTotal
    }, () => {

      // Later lines of code should go here

    })
}
Related Posts Related QUESTIONS :
  • Axios function not returning any values with js
  • How to use firestore TIMESTAMP to create time-stamp in JavaScript
  • Instantiate subclass without constructing
  • Outputing a created object in javascript to a server side JSON file
  • Transition the numeric labels in a bar chart
  • createBottomTabNavigator: hide just one tab from the tabBar
  • iife vs simple statement behavior with document.title
  • showDialogPopup Refresh Page after Click
  • Child component does not set the initial value passed from the parent: ReactJS
  • Nodejs javascript added to button not responding
  • Trying to define a promise.all
  • Python GEE to extract featurecollection timeseries from Landsat imageries
  • How to write negative binary number?
  • Unable to set property of individual object
  • Why Named Function Expression itself cannot assign Name to another Value?
  • How to reset scroll position on single page pagination
  • How to scroll to bottom of page, when a new message is sent - Socket.io
  • How to reconstruct audio blob from a base64 encoded String?
  • How to calculate numbers within an array of objects
  • Using JavaScript to change CSS properties of SVG circles for all circles that was not clicked
  • Is there value in propTypeing repeat required properties at every level of nested components?
  • Call function if variable does not exist in a filter
  • localStorage value doesn't get updated automatically
  • Direct native JavaScript or jQuery method to get containing block of an element
  • Dynamic JSON object to Html Table
  • How to send Id and file to same controller?
  • How to Make a jQuery Table Cell(td) clickable to Run a Function?
  • Prevent the duplicate function onchange event jQuery
  • Reactjs Input Upload doesn't return local URL
  • An unexpected 'StartObject' node was found when reading from the JSON reader. A 'PrimitiveValue' node was expected
  • How to filter a JSON Array, with an eventListener input value at keyup
  • How to separate the different properties of filter in css?
  • Why dont work change event of bootstrap input spinner?
  • How to hide overflow text content in react
  • Is there another way to write line 6
  • Cypress - how to find by text content?
  • How to setstate for the dynamic checkboxes in a loop in react?
  • Is display:none safe?
  • How to create a form to change part of a href url of a button?
  • Put many function inside function in Javascript
  • how to exit from loop after a ajax call
  • Do Angular Reactive Form Validator.min/max check Perform Type Conversions before checking the value?
  • How to Replace Text Within Script Tags Using JQuery
  • add variable to object if not undefined using short-hand
  • How can I effectively curve my items inside a list?
  • Add new record Keyboard Shortcut on Kendo Grid Mvc
  • Time and Date running on page
  • Looping through page links puppeteer doesn't return values from the newly loaded page
  • Problem with Navigator.geoLocation.getCurrentPosition not working
  • Trying to change the id of an element with Javascript
  • Embedded Schema Inserting Blank in Meteor using Collection2
  • avoid useEffect to render at first load?
  • Why is this CSS transition only working correctly on the some clicks? How to solve it?
  • Interpolated values does not reflect the latest values in an Angular app
  • Javascript classes define attribute in constructor or outside the class
  • How to block scroll event passing through to iframe until iframe is active?
  • What is the purpose of "constructor" method in javascript?
  • Stencil JS not working with non-default imports
  • Are frameworks misleadingly named for marketing purposes?
  • React <Redirect> after transition not working
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com