Home > Software design >  How to fetch image via GET request in React Native?
How to fetch image via GET request in React Native?

Time:09-02

I am currently taking the image as a json file in loadImage() but I'm busting and would like to know which would be the right mode. Other thing to know is that I get the photo_reference parameter only after the first fetch. I'm using Google Maps Place Photo API. From the first fetch I get a JSON file.

My code so far:

const CardResturant = ({ resturant }) => {
  const [isLoading, setLoading] = useState(true);
  const [info, setInfo] = useState([]);

  const [imagePlace, setImage] = useState([]);
  const [isLoadImage, setLoadImage] = useState(true);

  useEffect(() => {
    setLoading(false);
    fetch(
      `https://maps.googleapis.com/maps/api/place/details/json?place_id=${resturant.id}&key=KEY`
    )
      .then((response) => response.json())
      .then((json) => {
        setInfo(json);
        loadImage(json?.result?.photos[0].photo_reference);
      })
      .catch((error) => console.error(error))
      .finally(() => setLoading(true));
  }, []);

  const loadImage = (photo_reference) => {
    setLoadImage(false);
    fetch(
      `https://maps.googleapis.com/maps/api/place/photo?maxwidth=100&photo_reference=${photo_reference}&key=KEY`
    )
      .then((response) => response.json())
      .then((photo) => setImage(photo))
      .catch((error) => console.error(error))
      .finally(() => setLoadImage(true));
  };

  return (
    <View>
      {!isLoading ? (
        <Text>LOADING</Text>
      ) : (
        <View>
          <View>
            <Image ??help?? />
          </View>
        </View>
      )}
    </View>
  );
};

CodePudding user response:

You shouldn't be calling res.json() to parse an image. It should be res.blob(). That has been said, assuming you are trying to fetch one image, you could do it like so:

const [imagePlace, setImage] = useState(""); // initial it to an empty string
const loadImage = async (photo_reference) => {
  setLoadImage(false);
  try {
    const res = await fetch(
      `https://maps.googleapis.com/maps/api/place/photo?maxwidth=100&photo_reference=${photo_reference}&key=KEY`
    )
    const data = await res.blob();
    setImage(URL.createObjectURL(data));
  } catch (error) {
    console.error(error)
  }finally{
    setLoadImage(true)
  }
};

I'm using async/await just to have a better looking code. Your approach with then() would work as well. Finally change your JSX for rendering the image to:

{imagePlace ? (
  <Image source={{ uri: imagePlace }} style={{ width: 200, height: 200 }} />
) : (
  <></>
)}
  • Related