0

I want to retrieve a field (for now) from the promise and render it as the title in my pop-up modal. I got the promise to be resolved by using useEffect and it does populate my modal, however there is a slight delay for it to appear as it waits for the response to be set a value.

I tried playing around with creating another function below Modal in the same file to use aync/await, however I'm stumped in figuring out where to place them, as I keep getting errors for using it incorrectly, or nothing from the promise is passed back.

import React, { useState, useEffect } from 'react';
import './Modal.css';

 const Modal = ({close, item}) => {
    const [response, setResponse] = useState(null);
   useEffect(() => {
        item.then(object => setResponse(object.data.title))
   }, [])

    return (
   <div className='modal'>
       <div className='popup'>
           <h1>{response}</h1>
          <button onClick={ () => { close(false) }}>close me</button>
       </div>
   </div>
   );
}

export default Modal;
Winsome
  • 79
  • 1
  • 5
  • 12
  • use interval with js native or you can use it https://stackoverflow.com/questions/41364753/stop-rendering-of-a-component-after-componentdidmount – Fajrul Aulia Apr 16 '20 at 02:08
  • What is the behaviour you are looking for? Are you looking to defer the rendering of the entire Modal component until the response is returned? – wentjun Apr 16 '20 at 02:14

1 Answers1

0

The thing is, you are rendering the component and that component is waiting for the promise to be resolved, you should add the modal after the Promise has been resolved on the parent of the Modal component, don't try to pause execution, that's really problematic, just let react render using the common rules (if there's a new prop -> render, if there's a state change -> render), state changes assumes the actual component has been rendered already.

Sebastián Espinosa
  • 2,123
  • 13
  • 23
  • 1
    I ended up looking at my code again and moved a lot of code around to get it to work as you mentioned. Definitely a much better structure than before as I was confusing myself. ☕ – Winsome Apr 17 '20 at 00:57