Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useEffect shows data and then cannot read properties of undefined

I am getting data from a 3rd party API. When I console.log the data it shows in console but then is followed by Uncaught TypeError: Cannot read properties of undefined (reading 'tweet_results') I don’t actually get to see anything on the screen when I try the return as well, even though I have some conditions in there.

const LatestTweets = () => {
  const [tweets, setTweets] = useState([]);
  useEffect(() => {
    const getTweets = async () => {
      try {
        const response = await axios.get(
          "https://myendpoint.com"
        );

        setTweets(
          response.data.data.user.result.timeline.timeline.instructions[1]
            .entries
        );
      } catch (err) {
        console.log(err);
      }
    };
    getTweets();
  }, []);

  const test = tweets.map((t) => {
    console.log(t.content.itemContent.tweet_results.result.legacy.full_text);
  });

  return (
    <div>
      {tweets &&
        tweets.length &&
        tweets.map((t) => (
          <p>{t.content.itemContent.tweet_results.result.legacy.full_text}</p>
        ))}
    </div>
  );

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It seems like tweet_results can not contain in some objects from real data. So, to prevent from this error use ?. to go inside object.

const LatestTweets = () => {
  const [tweets, setTweets] = useState([]);
  useEffect(() => {
    const getTweets = async () => {
      try {
        const response = await axios.get(
          "https://myendpoint.com"
        );

        setTweets(
          response.data.data.user.result.timeline.timeline.instructions[1]
            .entries
        );
      } catch (err) {
        console.log(err);
      }
    };
    getTweets();
  }, []);

  const test = tweets.map((t) => {
    console.log(t.content?.itemContent?.tweet_results?.result?.legacy?.full_text);
  });

  return (
    <div>
      {tweets &&
        tweets.length &&
        tweets.map((t) => (
          <p>{t.content?.itemContent?.tweet_results?.result?.legacy.full_text}</p>
        ))}
    </div>
  );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading