React Native fetch URL - passing hook value as parameters

Viewed 79

What is the proper way to pass a useState hook value as a query parameter in a REACT NATIVE fetch url? The function returns that my jwt is malformed it's not reading the value of the hook properly. The two hooks are below, I'm trying to use those as query parameters in the fetch URL AND header authorization. $Are typically JQuery, but not sure the proper syntax for React Native - Expo.

const [user, setUser] = useState();
const [userID, setUserID] = useState();
const [subscriptions, setSubscriptions] = useState();

useEffect(() => {
    const fetchSubUploads = async (userID, user) => {
      const response = await fetch(
        `content/subs/uploads/**${userID}**`,{
        method: 'GET',
        headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer **${user}**`
        },
      });
      let data = await response.json();
      console.log(data);
      setSubscriptions(data.subscriptionUploads);
      return data;
    };

      const getUser = async() =>{
      const loggedInUser = await AsyncStorage.getItem('fariToken');
      if(!loggedInUser){
        Alert.alert('Please Login')
      }if(loggedInUser){
        setUser(JSON.stringify(loggedInUser))
      }
    }
    fetchSubUploads();
  }, []);
1 Answers

I suggest spitting the useEffect in two. One effect is obviously dealing with making the fetch request with the appropriate data, user and userID, and so should have a dependency on these values, while the other effect deals with loading some "initial" state values from storage.

Example:

const [user, setUser] = useState();
const [userID, setUserID] = useState();
const [subscriptions, setSubscriptions] = useState();

useEffect(() => {
  const getUser = async () => {
    const loggedInUser = await AsyncStorage.getItem('fariToken');
    
    if (loggedInUser) {
      setUser(JSON.stringify(loggedInUser));
    } else {
      Alert.alert('Please Login');
    }
  }

  getUser();
}, []);

useEffect(() => {
  const fetchSubUploads = async (userID, user) => {
    const response = await fetch(
      `content/subs/uploads/**${userID}**`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer **${user}**`
        },
      }
    );
    const data = await response.json();
    console.log(data);
    setSubscriptions(data.subscriptionUploads);
    return data;
  };

  if (user && userID) {
    fetchSubUploads(userID, user);
  }
}, [user, userID]);
Related