'Wait for redux to load the data
I want to extract an object from redux. I want to display the value when it is loaded. I don't know how to do it.
const user = useSelector((state) => state.user);
This is the code I wrote. It extracts the value from redux but initially, it is undefined. I want to perform a function when the value gets loaded completely. How can I do it?
Solution 1:[1]
You can do it by using conditional rendering for example:
const user = useSelector((state) => state.user);
{user && user.map(item=>(
<div>
<ul>
<li>{item.name}</li>
<ul>
</div>
)}
so if user is true then only map the user array, try this code in your render method of JSX.
Solution 2:[2]
Firstly what does the reducer state look like and also if you have named the reducer user as well as there being a user object in the initial state then you are going to have to look at using
like this
const { user } = useSelector((state) => state.user);
or like this
const user = useSelector((state) => state.user.user);
then where you use it if the user is undefined
and you want to render the user object once the user data has successfully updated
something like
<div>
{user && user.name}
{user && user.age}
{user && user.height}
</div>
or if you want to show all the data and there are no embedded properties
you could do something like
<div>
{Object.keys(user).length > 0 &&
Object.keys(user)
.map((key) =>
<div>{user[key]}</div>)
}
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Knightcrawler |
| Solution 2 | kodamace |
