setState doesn't update the state immediately
This callback is really messy. Just use async await instead:
async openAddBoardModal(){
await this.setState({ boardAddModalShow: true });
console.log(this.state.boardAddModalShow);
}
Console.log() after setState() doesn't return the updated state
setState()
is async (React docs), so the state changes won't be applied immediately. If you want to log out the new state,setState()
takes in a function as the second argument and performs that function when the state is updated. So:
this.setState({
abc: xyz
},
() => console.log(this.state.abc),
)
Or you can also use componentDidUpdate()
, which is recommended
Why is the state not updating when post method is done?
States are updated asynchronously so doing console.log after setState or invoking a method which use state just after that won't reflect the new state.
Use the below code which updates following in your code
- Return the URL from uploadImage so that it can be used in handleSubmit method.
- Use useEffect to show the form to log on console.
const handleSubmit = async (e) => {
e.preventDefault();
setModalShown(false);
const imageUrl = await uploadImage();
setForm({title: classTitle, classImageURL: imageUrl });
};
const uploadImage = async () => {
const formData = new FormData();
formData.append("file", imageSelected);
formData.append("upload_preset", "cloudinary_default");
const response = await Axios.post(
"https://api.cloudinary.com/v1_1/<userid>/image/upload",
formData
);
setUploadedImageURL(response.data.url);
return response.data.url;
};
useEffect(() => {
console.log(form)
}, [form]);
React setState not updating state
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');
});
Why does calling react setState method not mutate the state immediately?
From React's documentation:
setState()
does not immediately mutatethis.state
but creates a
pending state transition. Accessingthis.state
after calling this
method can potentially return the existing value. There is no
guarantee of synchronous operation of calls tosetState
and calls may
be batched for performance gains.
If you want a function to be executed after the state change occurs, pass it in as a callback.
this.setState({value: event.target.value}, function () {
console.log(this.state.value);
});
reactjs set hook method is not working after console.log
This is because React's setState functions are async, you won't see the state change right away. If you would wait a second you would see the value change.
console log the state after using useState doesn't return the current value
useState
by default simply does one thing and one thing only, set the new state and cause a re-render of the function. It is asynchronous in nature so by default, methods running after it usually run.
From your example, on a fresh load of the page, typing 's' causes useState to change the state, but because it is asynchronous, console.log
will be called with the old state value, i.e. undefined
(since you didn't set a value. You should consider setting an initial state, if you want to)
const [weather, setWeather] = useState(''); // Set the intial state
The only way to truly read the value of the state is to use useEffect
, which is called when there is a re-render of the component. Your method simply becomes:
import React, { useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
function Weather() {
const [weather, setWeather] = useState('');
useEffect(() => console.log(weather), [weather]);
const changeValue = event => setWeather(event.target.value);
return <input value={weather} onChange={changeValue} />;
}
const rootElement = document.getElementById('root');
ReactDOM.render(<Weather />, rootElement);
Related Topics
Non-Blocking Settimeout in JavaScript VS Sleep in Ruby
Sort JavaScript Array by Two Numeric Fields
Ruby with Watir: Handling JavaScript Popup Window
Why Is It Frowned Upon to Modify JavaScript Object's Prototypes
How to Trigger Jquery Change Event in Code
How to Use Ranges in a Switch Case Statement Using JavaScript
How to Change the HTML Content as It's Loading on the Page
The Mystery of the Disappearing Checkmarks
Why Is "This" in an Anonymous Function Undefined When Using Strict
JavaScript Regexp Dynamic Generation from Variables
Bitwise or in Ruby VS JavaScript
Updating Elements in Rails with Ajax
How to Scrape Data Using Ruby Which Is Generated by a JavaScript Function
Convert Array of Strings into an Array of Objects
Copy Output of a JavaScript Variable to the Clipboard
Rails 4 - Gmaps4Rails - Map Won't Render
Where Do the Parameters in a JavaScript Callback Function Come From