If I write
function Component() {
const [isLoading, setLoading] = useState(true);
const request = () => {
setLoading(true)
console.log(isLoading)
setLoading(false)
console.log(isLoading)
}
}
It will log out 'true' both times. Why isn't the state updating in the console? Eventhough it works fine in the DOM.
this.setState({ ...} will show the new state value
Setting a new value in state by using setState or useState hook is an asynchronous process.
If you want to log the new value once it has changed, you have to couple it with the useEffect hook
useEffect(() => {
console.log(isLoading)
}, [isLoading]);
Arnaud's answer is 100% correct, but what confused me when playing around with this stuff was that calling setState twice didn't have the same effect as trying to console.log directly after an update.
This is because of how React handles state updates internally, and even though your log may be wrong, your state is actually updated appropriately.
Related
I am building an app to understand the useState hook. This app simply has a form for entering username. I am trying to save the entered username. So, I have used react useState. And I tried to await the updating function of the useState in the event handler.
const usernameChangeHandler = async (event) => {
await setEnteredUsername(event.target.value);
console.log(enteredUsername, enteredAge);
};
And when I tried to log the username it doesn't show us the current state but the previous state. Why?
const usernameChangeHandler = async (event) => {
await setEnteredUsername(event.target.value);
console.log(enteredUsername, enteredAge);
};
enteredUsername is never going to change. It's a closure variable that's local to this single time you rendered the component. It's usually a const, but even if it was made with let, setEnteredUsername does not even attempt to change its value. What setEnteredUsername does is ask react to rerender the component. When the render eventually happens, a new local variable will be created with the new value, but code from your old render has no access to that.
If you need to run some code after calling setEnteredUsername, but you don't actually care if the component has rerendered yet, the just use the value in event.target.value, since you know that's going to be the new value of the state:
const usernameChangeHandler = (event) => {
setEnteredUsername(event.target.value);
console.log(event.target.value, enteredAge);
}
If instead you need to make make sure that the component has rerendered and then do something after that, you can put your code in a useEffect. Effects run after rendering, and you can use the dependency array to make it only run if the values you care about have changed:
const [enteredUsername, setEnteredUsername] = useState('');
useEffect(() => {
console.log('rendering complete, with new username', enteredUsername);
}, [enteredUsername]);
const usernameChangeHandler = (event) => {
setEnteredUsername(event.target.value);
};
the act of setting state is asynchronous; therefore, console logging directly after setting your state will not accurately provide you with how state currently looks. Instead as many have suggested you can utilize the useEffect lifecycle hook to listen for changes in your enteredUserName state like so:
useEffect(() => {
console.log(enteredUsername);
}, [enteredUsername]);
listening for changes within the useEffect will allow you to create side effects once state has updated and caused your component to rerender. This in turn will trigger your useEffect with the enteredUsername dependency, as the enteredUserName state has changed.
I hope this won't get flagged as a duplicate because none of identical problems reflect my issue totally.
So the issue i'm having is i have a useEffect hook like this:
useEffect(()=>{
console.log("opening websocket");
websocket.current=new WebSocket(`ws://127.0.0.1:8000/chat/${curMessage.receiverUsername}/${curUserName}/`);
websocket.current.onopen= (event)=>{
console.log("open:",event)
}
websocket.current.onclose= (event)=>{
setSentMessages([]);
console.log("close:",event,sentMessages);
}
websocket.current.onmessage=(event)=>{
console.log("new message",event);
console.log(JSON.parse(event.data));
setSentMessages([...sentMessages,JSON.parse(event.data)]);
setCont([...cont,1,2]);
console.log(sentMessages);
}
setSentMessages([]);
},[curMessage,curUserName]);
the variable curMessage gets it value from redux state and since it's in the dependency array in the useEffect changes should be reflected immediately the changes are made in the redux state,this work correctly except for the setSentMessages([]) at the last line in the useEffect,the state sentMessages never gets updated immediately the useEffect is triggered which results to still getting old values instead of an empty array,everything else works fine and updates in the useEffect when it gets triggered,i have tried making placing setSentMessages([]) in another useEffect which is dependent on another state but still the same result.
const [sentMessages, setSentMessages] = useState([
// some initial state here
]);
const sentMessagesRef = useRef([
// some initial state here
]);
useEffect(() => {
// Keep ref in sync with state
sentMessagesRef.current = sentMessages;
}, [sentMessages]);
useEffect(
() => {
websocket.current.onmessage = (event) => {
// Use up-to-date value of sentMessages here,
// not the value at the time of declaring this function.
setSentMessages([...sentMessagesRef.current, JSON.parse(event.data)]);
}
setSentMessages([]);
},
[curMessage, curUserName]
);
I believe your issue is that setSentMessages([]) is in fact working, but the onmessage function then overwrites that state with the outdated value. The state is updated immediately, but your callback uses a stale reference of sentMessages. Copying the state to a ref and then accessing that fixes it.
In my React application, I have a useEffect that checks if an element has the display style none set to it. If it does then it should set the state to false, however it always comes back as undefined.
const [testingProp, setTestingProp] = useState();
useEffect(() => {
const styles = getComputedStyle(customerPropertyTypeSection.current);
if (styles.display == 'none') {
setTestingProp(false);
console.log('style set to none'); // this prints
console.log(testingProp); // this prints 'undefined'
}
}, []);
setState in React acts like an async function.
So putting a console.log(state) right after setting it, will most likely show the former value, which is undefined in this case, as it doesn't actually finish updating the state until the log command runs.
You can use a deticated useEffect hook with the relevant state as a dependency to act upon a change in the state.
Example:
useEffect(() => {
console.log(state);
}, [state]);
Basically, the callback function in the example will run every time the state changes.
P.S. - maybe you can do without the useEffect you are using here to populate the state.
If you have access to customerPropertyTypeSection.current initially, you can do something like this:
const [testingProp, setTestingProp] = useState(() => {
const styles = getComputedStyle(customerPropertyTypeSection.current);
return styles.display !== 'none';
});
If the example above works for you, then the useEffect you are using is redundant and can be removed.
When using flags in redux state and class-based components, life is good. You start your API calls in componentWillMount and by the time the component is mounted and the render() function runs, you have your flags set correctly in redux, meaning no flash of unwanted content (FUC).
That is well, but we are using functional components now. In that case, we run API calls through useEffect(), meaning we set the flags in redux only on second render. In the case of a simple component:
function SimpleComponent() {
const isLoading = useSelector(selectIsLoading);
const dispatch = useDispatch();
useEffect(() => {
dispatch(startApiRequest());
},[dispatch]);
if (isLoading) {
return <LoadingComponent />;
}
return <ContentThatWillBreakIfApiCallIsNotFinished />;
}
The behaviour of this code is as follows:
render 1: isLoading is false, you show broken content.
after render 1: useEffect runs, sets isLoading to true
render 2: isLoading is true, you no longer show broken content
A simple solution is to init the store with isLoading set to true. That means that you will have to make sure to always return it to true when exiting components. This can lead to bugs if the same flag is used in multiple components. It is not an ideal solution.
With redux-thunk, we can use a custom hook that has internal isLoading flag and not set the flag in redux. Something like:
const apiCallWithLoadingIndicator = () => {
const [isLoading, setIsLoading] = useState(true);
const dispatch = useDispatch();
useEffect(() => {
(async () => {
await dispatch(asyncThunkReturningPromise());
setIsLoading(false);
})()
}, [setIsLoading, dispatch]);
return isLoading;
}
There doesn't seem to be a simple way of achieving this with redux-saga, where generators are used instead of promises. What is the best practice for handling loading flags with functional components in redux-saga?
Generally: componentWillMount has been deprecated for years and will probably be removed in React 18 - you should not be using that in class components either.
That said, usually it helps to just start off the initial state with something like a "uninitialized" state value that tells you that, while it is not loading, it also hasn't even started doing anything yet and to handle that the same as "loading" in your component.
Why does React Hooks Axios API Call return twice.. even with a check if it's loaded?
I am used to this.setState but trying to understand the reason behind this why it's showing up twice inside my console log.
My code:
import React, { useState, useEffect } from "react";
import axios from "axios";
const App = () => {
const [users, setUsers] = useState({ results: [] });
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
await axios
.get("https://jsonplaceholder.typicode.com/users/")
.then(result => setUsers(result));
setIsLoading(false);
};
fetchData();
}, []);
console.log(
users.status === 200 && users.data.map(name => console.log(name))
);
return <h2>App</h2>;
};
export default App;
For the fire twice, perhaps is one time from componentDidMount, and the other one from componentDidUpdate
https://reactjs.org/docs/hooks-effect.html
Does useEffect run after every render? Yes! By default, it runs both after the first render and after every update. (We will later talk about how to customize this.) Instead of thinking in terms of “mounting” and “updating”, you might find it easier to think that effects happen “after render”. React guarantees the DOM has been updated by the time it runs the effects.
You did not check 'isLoading' before you fire the API call
// Only load when is not loading
if (!isLoading) {
fetchData();
}
This is actually normal behavior. This is just how functional components work with useEffect(). In a class component the "this" keyword is mutated when the state changes. In functional components with hooks the function is called again, and each function has its own state. Since you updated state twice the function was called twice.
You can read these 2 very in dept articles by one of the creators of react hooks for more details.
https://overreacted.io/a-complete-guide-to-useeffect/
https://overreacted.io/how-are-function-components-different-from-classes/
Even I had a similar issue. in my case useEffect() was called twice because the parent component was re-rendered because of a data change.