search

Home  >  Q&A  >  body text

Uncaught TypeError: Cannot read property of undefined (read 'img1') in promise

<p>I'm using react.js</p> <pre class="brush:php;toolbar:false;">async function Banners(props) { const response = await axios.get(`${apiUrl}/assets/get`); return ( <MainContent text={response.text} img1={props.img1 ? props.img1 : response.data.img1} img2={props.img2 ? props.img2 : response.data.img2} /> ); }</pre> <p>The error will only occur when "async" is present</p>
P粉265724930P粉265724930446 days ago552

reply all(1)I'll reply

  • P粉207969787

    P粉2079697872023-08-26 14:12:53

    You need to wrap the asynchronous API call in useEffect Hook and store the data in the state so that you can use the state in the render function. Here is a sample code without tests:

    function Banners(props) {
      const [response, setResponse] = useState([]);
    
      const fetchData = async () => {
        const response = await axios.get(`${apiUrl}/assets/get`);
        setResponse(response);
      };
    
      useEffect(() => {
        fetchData();
      }, []);
    
      return (
        <MainContent
          text={response.text}
          img1={props.img1 ? props.img1 : response.data.img1}
          img2={props.img2 ? props.img2 : response.data.img2}
        />
      );
    }

    reply
    0
  • Cancelreply