Данные, отображаемые в Reactjs, не меняются после первого вызова конечной точки - PullRequest
0 голосов
/ 05 августа 2020

У меня есть приложение, которое отображает данные из API в виде списка. Когда я запускаю сервер и вхожу в систему, данные передаются клиенту. Если бы мне пришлось войти в систему как другой пользователь с другими данными, данные от предыдущего пользователя отобразились бы, как если бы конечная точка не обновлялась. Я вижу, что данные конечной точки меняются, но не могу понять, почему новые данные не отображаются. Любая помощь будет принята с благодарностью, заранее спасибо.

Вот функция, которая делает запрос GET к конечной точке api. Он асинхронный и использует npm twit для использования API твиттера:

const returnNonfollowers = (screenName) => {

  T.get('followers/ids', { screen_name: screenName, count: 5000, stringify_ids: true }, function (err, data, response) {
    followers = data.ids; 

    T.get('friends/ids', { screen_name: screenName, count: 5000, stringify_ids: true }, function (err, data, response) {
      friends = data.ids;
      let difference = friends.filter(x => followers.toString().indexOf(x) == -1);

      T.get('users/lookup', { user_id: [difference[0], difference[1], difference[2], difference[4]] }, function (err, data, response) {
        router.get('/nonfollowers', async (req, res) => {
          res.send({ nonfollowers: data });
        })

      })

    })

  })
}

Вот функция, вызываемая, когда пользователь аутентифицирует свою учетную запись твиттера:

passport.use(
  new TwitterStrategy(
    {
      consumerKey: keys.TWITTER_CONSUMER_KEY,
      consumerSecret: keys.TWITTER_CONSUMER_SECRET,
      callbackURL: "http://twitscouter.com/auth/twitter/redirect"
    },
    async (token, tokenSecret, profile, done) => {
      //console.log(profile._json.screen_name);

      returnNonfollowers(profile._json.screen_name);

      // Find current user in UserModel
      const currentUser = await User.findOne({
        twitterId: profile._json.id_str
      });
      // Create new user if the database doesn't have this user
      if (!currentUser) {
        const newUser = await new User({
          name: profile._json.name,
          screenName: profile._json.screen_name,
          twitterId: profile._json.id_str,
          profileImageUrl: profile._json.profile_image_url
        }).save();
        if (newUser) {
          done(null, newUser);
        }
      }
      done(null, currentUser);
    }
  )
);

Вот запрос на выборку на стороне клиента:

componentDidMount() {

        fetch('/users/nonfollowers',
            {
                method: "GET",
                credentials: "include",
                headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json",
                    "Access-Control-Allow-Credentials": true,
                }
            })
            .then(response => response.json())
            .then(data => {
                this.setState({
                    users: [
                        {
                            nonfollower: data.nonfollowers[0].screen_name,
                            profileImg: data.nonfollowers[0].profile_image_url
                        },
                        {
                            nonfollower: data.nonfollowers[1].screen_name,
                            profileImg: data.nonfollowers[1].profile_image_url
                        },
                        {
                            nonfollower: data.nonfollowers[2].screen_name,
                            profileImg: data.nonfollowers[2].profile_image_url
                        },
                        {
                            nonfollower: data.nonfollowers[3].screen_name,
                            profileImg: data.nonfollowers[3].profile_image_url
                        }
                    ]
                })
            });
    }

Данные отображаются здесь (после получения данных this.setState changes обновляет массив и сопоставляется со списком на странице. После первой выборки он никогда не обновляет снова):


    render() {
        let nameList = this.state.users.map(nonMoot => {
            return (
                <Container>
                    <List nonMoot={nonMoot} />
                </Container>
            )
        })
        return (
            <div className="main">
                    <Container>
                        These are the users that are not following you back
                        {nameList}
                    </Container>
            </div>
        )
    }
...