Uncaught TypeError: Cannot read property of undefined (read 'img1') in promise
P粉265724930
P粉265724930 2023-08-25 16:53:18
0
1
601
<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粉265724930
P粉265724930

reply all(1)
P粉207969787

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}
    />
  );
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template