Skip to content
Advertisement

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>
  );

Advertisement

Answer

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>
  );
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement