'Handle state variable initialization
I'm trying to fill form data using state variable. Data of state variable is getting from redux store as shown below :
const [location, setLocation] = useState(post && post.location);
const [hastage, setHastage] = useState(post && post.hastage);
const [caption, setCaption] = useState(post && post.caption);
const [postImg, setPostImg] = useState(post && post.postImg);
In above code 'post' is redux store instance.
Every thing is working Fine. However, Problem is that :
When I refresh page 'post' data is async call therefore before getting post data all variable is initialized with " "(Blank). and form is getting empty.
Hoe to initialize all state variable after 'post' data is ready ?
Solution 1:[1]
You can use an useEffect with post as a dependency, where it updates all states values if post exists.
useEffect(() => {
if (post) {
setLocation(post.location)
setHastage(post.hastage)
setCaption(post.caption)
setPostImg(post.postImg)
}
}, [post])
Solution 2:[2]
You can make use of a conditional expression which only returns the form if the data has some value in it and when its fetching some value you could do something like a loading screen or a spinner hiding the form,etc. You could technically add an extra value in redux just for tracking this and when that value changes you display the form. Also you could try to disable the form fields just as a extra suggestion.
return (<div>{post.hasLoaded ? <MyForm /> : 'Loading...'}</div>);
or
return (<div>{post && post.location ? <MyForm />:'Loading..'}</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 | Ruben Paredes |
| Solution 2 |
