'how to prevent getting multiple responses in Axios react native?
I want to get data from database. the function CurrentUserId get the details of the current user. i need to get data using GetTemplate function the problem is that i get multiple response contains the same data. I don't know where is the problem
  const [id, setId] = useState("");
  const [data, setdata] = useState("");
  const CurrentUserID = async () => {
    const token = await AsyncStorage.getItem("token");
    fetch("/", {
      headers: new Headers({
        Authorization: "Bearer " + token,
      }),
    })
      .then((res) => res.json())
      .then((data) => {
        // console.log(data);
        setId(data._id);
        console.log(id);
      });
  };
  const GetTemplates = async () => {
    await axios
      .get(`/api/user/${id}`)
      .then((response) => {
        setdata(response.data);
      })
      .catch(function (error) {
        console.log(error);
      });
  };
useEffect(() => {
  CurrentUserID();
  GetTemplates();
}, []);
Solution 1:[1]
I think we should call GetTemplates() only after id is present. Currently you are calling GetTemplates() on initial render in useEffect even before id is set.
const [id, setId] = useState("");
const [data, setdata] = useState("");
useEffect(() => {
  CurrentUserID();
}, []);
// Get Templates only when id changes
useEffect(() => {
  if (!id) return; // Initial Render, If id is empty do nothing
  GetTemplates();
}, [id]);
const CurrentUserID = async () => {
  const token = await AsyncStorage.getItem("token");
  fetch("/", {
      headers: new Headers({
        Authorization: "Bearer " + token,
      }),
    })
    .then((res) => res.json())
    .then((data) => {
      // console.log(data);
      setId(data._id);
      console.log(id);
    });
};
const GetTemplates = async () => {
  await axios
    .get(`/api/user/${id}`)
    .then((response) => {
      setdata(response.data);
    })
    .catch(function(error) {
      console.log(error);
    });
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | PR7 | 
