2

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. Another 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>
  );
};
0

1 Answer 1

4

You shouldn't call 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(""); // initialize it to an empty string
const loadImage = async (photo_reference) => {
  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)
  }
};

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 }} />
) : (
  <></>
)}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.