Twitter user search to display name, followers, following, among others using React.js

193 views Asked by At

I am fairly new to react.js and I'm just trying my hands on a few random projects i can think of and one of them is to make a search engine in react.js that looks up users on twitter by simply entering their name in a search bar and the result will display their details using the Twitter API. However, when doing this i am hit with the follwoing errors in console: Error ocuring

App.js:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const App = ({ username }) => {

  const [user, setUser] = useState({});
  const [tweets, setTweets] = useState({});
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
        try {
            const { data: user } = await axios.get(`https://api.twitter.com/1.1/users/show.json?screen_name=${username}`, {
              method : "GET",
                headers: {
                    Authorization: `Bearer <YOUR_TOKEN>`
                }
            });
            const { data: tweets } = await axios.get(`https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=${username}&count=200`, {
              method : "GET",
                headers: {
                    Authorization: `Bearer <YOUR_TOKEN>`
                }
            });
            setUser(user);
            setTweets(tweets);
        } catch (error) {
            setError(error);
        }
    };
    fetchData();
  }, [username]);

  if (error) {
    return <div>An error occurred: {error.message}</div>;
  }

  return (
    <div>
      <h1>{user.name}</h1>
      <p>Username: {user.screen_name}</p>
      <p>Followers: {user.followers_count}</p>
      <p>Following: {user.friends_count}</p>
      <p>Bio: {user.description}</p>
      <p>Date Joined: {user.created_at}</p>
      <p>Pinned Tweet: {user.status ? user.status.text : 'No Pinned Tweet'}</p>
      <p>Total Tweets: {user.statuses_count}</p>
    </div>
  );
};

export default App;

UPDATE

I have added the search box feature to the code but I'm still getting the same errors

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const TWITTER_API_URL = 'https://api.twitter.com/1.1/users/search.json';

function App() {
  const [username, setUsername] = useState('');
  const [userData, setUserData] = useState({});
  const [searchValue, setSearchValue] = useState('');

  useEffect(() => {
    if (searchValue) {
      axios
        .get(TWITTER_API_URL, {
          params: {
            q: searchValue,
            count: 1
          },
          headers: {
            'Authorization': 'Bearer YOUR_BEARER_TOKEN'
          }
        })
        .then(response => {
          setUsername(response.data[0].screen_name);
        })
        .catch(error => {
          console.log(error);
        });
    }
  }, [searchValue]);

  useEffect(() => {
    if (username) {
      axios
        .get(`https://api.twitter.com/1.1/users/show.json?screen_name=${username}`, {
          headers: {
            'Authorization': 'Bearer YOUR_BEARER_TOKEN'
          }
        })
        .then(response => {
          setUserData(response.data);
        })
        .catch(error => {
          console.log(error);
        });
    }
  }, [username]);

  return (
    <div>
      <input
        type="text"
        placeholder="Search by name"
        value={searchValue}
        onChange={e => setSearchValue(e.target.value)}
      />
      {username && (
        <div>
          <p>Username: {username}</p>
          <p>Name: {userData.name}</p>
          <p>Following: {userData.friends_count}</p>
          <p>Followers: {userData.followers_count}</p>
          <p>Bio: {userData.description}</p>
          <p>Date Joined: {userData.created_at}</p>
          <p>Pinned Tweet: {userData.status.text}</p>
          <p>Total Tweets: {userData.statuses_count}</p>
        </div>
      )}
    </div>
  );
}

export default App;

I would appreiciate any help given to resolve this issue. Thank you.

1

There are 1 answers

2
Kevin On

I would advise you to move the const fetchData = async () => { ... outside the useEffect() and may sound silly, but for the Authorization: Bearer <YOUR_TOKEN> have you changed the <YOUR_TOKEN> with your actual token? Lastly, you don't need method : "GET" because you are doing axios.get( ...

Please try this code:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const App = ({ username }) => {

  const [user, setUser] = useState({});
  const [tweets, setTweets] = useState({});
  const [error, setError] = useState(null);

 
    const fetchData = async () => {
        try {
            const { data: user } = await axios.get(`https://api.twitter.com/1.1/users/show.json?screen_name=${username}`, {           
                headers: {
                    Authorization: `Bearer <YOUR_TOKEN>`
                }
            });
            const { data: tweets } = await axios.get(`https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=${username}&count=200`, {
                headers: {
                    Authorization: `Bearer <YOUR_TOKEN>`
                }
            });
            setUser(user);
            setTweets(tweets);
        } catch (error) {
            setError(error);
        }
    };

 useEffect(() => {
    fetchData();
  }, [username]);

  if (error) {
    return <div>An error occurred: {error.message}</div>;
  }

  return (
    <div>
      <h1>{user.name}</h1>
      <p>Username: {user.screen_name}</p>
      <p>Followers: {user.followers_count}</p>
      <p>Following: {user.friends_count}</p>
      <p>Bio: {user.description}</p>
      <p>Date Joined: {user.created_at}</p>
      <p>Pinned Tweet: {user.status ? user.status.text : 'No Pinned Tweet'}</p>
      <p>Total Tweets: {user.statuses_count}</p>
    </div>
  );
};

export default App;