Sunday, 19 June 2022

Looping through array, fetching tweets and returning new reversed array javascript react

UPDATE: I have deployed the site for more context you can view it here https://conundrum-quest-rw-rebuild-web.onrender.com/

the public repo is here

https://github.com/wispyco/conundrum-quest-rw-rebuild

Note: the data on the live site is different but the initial load is loading the hero's on the wrong cards, you can compare the quest with subsequent heros on the home page and the returned data from my function below, you can scroll down to see the rendered cards.

You can see that if you click on a card it shows the correct heros on the single page.


I have the following quests data structure that I am looping through in a separate function and running a fetch to request some profile images from twitter.

[
  {
    "__typename": "Quest",
    "id": 5,
    "name": "How do we solve mental health related issues?",
    "userId": 17,
    "heros": [
      {
        "__typename": "Hero",
        "name": "Anders Kitson",
        "twitter": "anderskitson"
      },
      {
        "__typename": "Hero",
        "name": "ders",
        "twitter": "derz_O"
      }
    ]
  },
  {
    "__typename": "Quest",
    "id": 6,
    "name": "How do we create a world where North Korea participates and collaborates with the rest of the World?",
    "userId": 17,
    "heros": [
      {
        "__typename": "Hero",
        "name": "Crypto Dude",
        "twitter": "phunk2243"
      }
    ]
  }
]

Here is my custom hook

const twitter = useFetchTwitterMultipleQuests(quests)

export const useFetchTwitterMultipleQuests = (twitterProfileManyQuests) => {
  const [twitter, setTwitter] = useState([])

  useEffect(() => {
    twitterProfileManyQuests.forEach(async (twitterProfileMany, i) => {
      const woop = twitterProfileMany.heros.map(async (twitterProfile) => {
        const test = fetch(
          `${window.location.origin}/.redwood/functions/twitter`,
          {
            method: 'POST',
            body: JSON.stringify({ twitter: twitterProfile.twitter }),
          }
        )
          .then(function (response) {
            // The response is a Response instance.
            // You parse the data into a useable format using `.json()`
            console.log('test')
            return response.json()
          })
          .then(function (data) {
            return data.data.resultAwaited.data
          })

        const go = await test

        return go
      })

      const june = await Promise.all(woop)

      setTwitter((prevState) => {
        return [...prevState, june]
      })
    })
  }, [twitterProfileManyQuests])

  const reversedTwitter = twitter.reverse()

  return reversedTwitter
}

The problem is the reversedTwitter or twitter variable in the end sometimes is in the correct reversed order and sometimes not reversed, and I can't figure out why.

This is the correct order result

[
  [
    {
      "username": "anderskitson",
      "profile_image_url": "https://pbs.twimg.com/profile_images/1428160652237889539/I7ZiM_g8_normal.jpg",
      "name": "▲nders on a quest 🜸 to see myself 🪞",
      "id": "4633808432"
    },
    {
      "profile_image_url": "https://pbs.twimg.com/profile_images/1496985668043436033/NoyLrUys_normal.jpg",
      "name": "ders.eth",
      "id": "1389695824934834181",
      "username": "derz_O"
    }
  ],
  [
    {
      "username": "phunk2243",
      "profile_image_url": "https://pbs.twimg.com/profile_images/1536485988767350784/cfP_sPSC_normal.jpg",
      "name": "9999999333 (🅱️uilding 35 Phunks) 🔜",
      "id": "1355005208259133442"
    }
  ]
]

This is the incorrect order result

[
  [
    {
      "name": "9999999333 (🅱️uilding 35 Phunks) 🔜",
      "profile_image_url": "https://pbs.twimg.com/profile_images/1536485988767350784/cfP_sPSC_normal.jpg",
      "username": "phunk2243",
      "id": "1355005208259133442"
    }
  ],
  [
    {
      "username": "anderskitson",
      "profile_image_url": "https://pbs.twimg.com/profile_images/1428160652237889539/I7ZiM_g8_normal.jpg",
      "name": "▲nders on a quest 🜸 to see myself 🪞",
      "id": "4633808432"
    },
    {
      "username": "derz_O",
      "profile_image_url": "https://pbs.twimg.com/profile_images/1496985668043436033/NoyLrUys_normal.jpg",
      "name": "ders.eth",
      "id": "1389695824934834181"
    }
  ]
]

The reason this matters is how I am rendering the data. I am rendering a Quest from the quests data, then mapping over the heros in a quest which correspond to the twitter profiles.

See Here

{quests.map((quest, i) => (
    <QuestCard key={quest.id}>
        <Link to={routes.quest({ id: quest.id })} key={quest.id}>
            <div>
                <h3>{truncate(quest.name)}</h3>
                {quest.heros.map((hero, index) => (
                    <React.Fragment key={hero.id}>
                        {twitter.length > 0 && twitter[i] && (
                            <span>
                                {hero.name}
                                <p>{twitter[i][index]?.name}</p>
                                <img
                                    key={i}
                                    src={twitter[i][index]?.profile_image_url}
                                    alt={twitter[i][index]?.name}
                                />
                            </span>
                        )}
                    </React.Fragment>
                ))}
            </div>
        </Link>
        <div className="clear" />
    </QuestCard>
))}

Any help would be greatly appreciated, most of what I have done works, but after about three refreshes the ordering breaks. Thanks



from Looping through array, fetching tweets and returning new reversed array javascript react

No comments:

Post a Comment