Search code examples
reactjsweb-deploymentmern

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

  • You should initialize all state value inside of a useEffect hook, which can allow you to perform some execution after after the DOM have been rendered.

    Firstly you 'll initialize all state to an empty string like this

    const [location, setLocation] = useState('');
    const [hastage, setHastage] = useState('');
    const [caption, setCaption] = useState('');
    const [postImg, setPostImg] = useState('');
    

    And in the second place you will add useEffect which will allow you to perform side effect

    useEffect(() => {
        // here you can check for existence of any attribute on the `post` object
        if(post && post.location) {
            setLocation(post.location);
        }
        // etc.
    }, [post]);
    

    You can also pass the post object to the second argument of the useEffect hook, this will trigger the rerender of the component each time the value of post change.