Can I await the update function of the useState hook - reactjs

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.

Related

RXJS subscribe callback doesn't have access to current react state (functional component)

I am using React with functional components in combination with useState() and RxJs.
I'm subscribing to a BehaviorSubject in my useEffect[] and everytime a new message is published, I want to check the current state of my component to decide which steps to take.
But: Even though in my program flow I can clearly see that my state has a certain value, the subscribe callback always only shows the initial empty value. When I stop execution in the middle of the callback, I can see that the "outdated" state is in the closure of the callback.
Why is this?
I've broken it down to those essential code parts:
function DesignView() {
const [name, setName] = useState("");
useEffect(() => {
console.log(name); // <--- This always shows correctly, of course
}, [name]);
useEffect(() => {
// even if this is the ONLY place I use setName() ... it doesn't work
setName("Test Test Test Test");
let subscription = directionService.getDirection().subscribe(() => {
console.log(name); // <--- this only ever shows "" and never "Test Test Test Test"
// no matter at what point of time the published messages arrive!
});
return () => {
subscription.unsubscribe();
}
}, []);
return (
...
);
}
The cause of this problem is that a non-react callback only ever sees a static copy of the state. The same problem appears in the useEffect cleanup function.
Solution:
Either
Add a ref to the state variable. Change the ref.current whenever the state changes and use the ref in the callback
Add the state variable to the dependency array of useEffect and unsubscribe/subscribe every time

React make an async call on data after retrieving it from the state

I need to make an async call after I get some data from a custom hook. My problem is that when I do it causes an infinite loop.
export function useFarmInfo(): {
[chainId in ChainId]: StakingBasic[];
} {
return {
[ChainId.MATIC]: Object.values(useDefaultFarmList()[ChainId.MATIC]),
[ChainId.MUMBAI]: [],
};
}
// hook to grab state from the state
const lpFarms = useFarmInfo();
const dualFarms = useDualFarmInfo();
//Memoize the pairs
const pairLists = useMemo(() => {
const stakingPairLists = lpFarms[chainIdOrDefault].map((item) => item.pair);
const dualPairLists = dualFarms[chainIdOrDefault].map((item) => item.pair);
return stakingPairLists.concat(dualPairLists);
}, [chainIdOrDefault, lpFarms, dualFarms]);
//Grab the bulk data results from the web
useEffect(() => {
getBulkPairData(pairLists).then((data) => setBulkPairs(data));
}, [pairLists]);
I think whats happening is that when I set the state it re-renders which causes hook to grab the farms from the state to be reset, and it creates an infinite loop.
I tried to move the getBulkPairData into the memoized function, but that's not meant to handle promises.
How do I properly make an async call after retrieving data from my hooks?
I am not sure if I can give you a solution to your problem, but I can give you some hints on how to find out the cause:
First you can find out if the useEffect hook gets triggered too often because its dependency changes too often, or if the components that contains your code gets re-mounted over and over again:
Remove the dependency of your useEffect hook and see if it still gets triggered too often. If so, your problem lies outside of your component.
If not, find out if the dependencies of your useMemo hook change unexpectedly:
useEffect(()=>console.log("chainIdOrDefault changed"), [chainIdOrDefault]);
useEffect(()=>console.log("lpFarms changed"), [lpFarms]);
useEffect(()=>console.log("dualFarms changed"), [dualFarms]);
I assume, this is the most likely reason - maybe useFarmInfo or useDualFarmInfo create new objects on each render (even if these objects contain the same data on each render, they might not be identical). If so, either change these hooks and add some memoization (if you have access to your code) or narrow down the dependencies of your pairLists:
const pairLists = useMemo(() => {
const stakingPairLists = lpFarms[chainIdOrDefault].map((item) => item.pair);
const dualPairLists = dualFarms[chainIdOrDefault].map((item) => item.pair);
return stakingPairLists.concat(dualPairLists);
}, [lpFarms[chainIdOrDefault], dualFarms[chainIdOrDefault]]);

React useState hook always comes as undefined when setting it in useEffect

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.

Setting Redux state as a default state when using React Hooks

I have a redux action that fetches all data and stores it into a global Redux store.
I want to store that state in a local state using Hooks so that the actual state doesn't get changed when I change it locally.
What I am doing right now is,
const [filteredTable, setFilteredTable] = useState([])
useEffect(() => {
props.fetchDatabase();
props.fetchOptions();
setFilteredTable(props.filtered_table_data);
}, [])
In useEffect, the props.fetchDatabase() gets the props.filtered_table_data and I can see that when I console.log it out.
However, when I use Hooks to store it into a local state and check if it's in there,
console.log(filteredTable, 'filteredTable')
just gives me [].
What am I doing wrong?
I believe the props.fetchDatabase() call is asynchronous, so by the time you are attempting to setFilteredTable the props.filtered_table_data has not updated yet.
You can try something like this:
useEffect(() => {
props.fetchDatabase();
props.fetchOptions();
}, [])
useEffect(() => {
setFilteredTable(props.filtered_table_data);
}, [props.filtered_table_data]);
Note that this effect will run every time filtered_table_data changes, so you may need to wrap around the code in the callback with some sort of condition if you want to restrict setting the local state.
useEffect's callback with [] as hook's second argument is only being called once when component just mounted. Inside it fetchDatabase, and fetchOptions callbacks are called, and right after that (when data isn't yet fetched) you call setFilteredTable, that's why there are empty array occurs in filteredTable.
Not sure if this answers your question, but React-Redux provides some hooks for accessing the redux store.
The one that might be of interest to you is the useSelector() hook.
Here's an example usage:
import { useSelector } from 'react-redux';
const App = () => {
const tableData = useSelector(state => state.tableData);
...
}

React hooks states aren't updating in log

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.

Resources