Taha Yıldırım
Taha Yıldırım

Reputation: 25

Making a request to another api after the response from the first api I get

I want to get the res.data.login information from the res.data information from the first api and send it to the second api

Then I want to get the result from the second api

const [user, setUser] = useState(null);
const [projects,setProjects]=useState(null)

useEffect(() => {
axios.get("http://localhost:5000/user", {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  })
  .then((res) => {
    setUser(res.data);
  })
  .catch((error) => {
    console.log("error " + error);
  });

const username = user.login
axios.get(`http://localhost:5000/projects`,{
    headers:{
      username:username,
    }
  }).then((response)=>{
    setProjects(response.data)
  })
}, []);

I looked for similar problems but couldn't find a solution.

Upvotes: 0

Views: 421

Answers (2)

Phil
Phil

Reputation: 165069

Two options...

Option 1

Move the second Axios call into the .then() from the first

useEffect(() => {
  axios
    .get("http://localhost:5000/user", {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })
    .then(({ data: userData }) => {
      setUser(userData);

      return axios
        .get("http://localhost:5000/projects", {
          headers: { username: userData.login }, // use response data here
        })
        .then(({ data: projectsData }) => {
          setProjects(projectsData);
        });
    })
    .catch(console.error);
}, []);

Option 2

Fire the second request in an effect hook with user as a dependency

useEffect(() => {
  axios
    .get("http://localhost:5000/user", {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })
    .then(({ data }) => {
      setUser(data);
    })
    .catch(console.error);
}, []);

useEffect(() => {
  if (user) { // only run once user is not null
    axios
      .get("http://localhost:5000/projects", {
        headers: { username: user.login }, // use state data here
      })
      .then(({ data }) => {
        setProjects(data);
      })
      .catch(console.error);
  }
}, [user]);

Upvotes: 1

Liki Crus
Liki Crus

Reputation: 2062

You need to get the user's info to get the project you may want to call the first API fetching synchronously.

But we can't call a function synchronously by await in useEffect hook.

There is a solution. Please define async function and run 2 API fetch functions inside it.

Here is a hook code.

  useEffect(() => {
    const asyncFunc = async () => {
      const res = await axios.get("http://localhost:5000/user", {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      setUser(res.data);

      axios.get(`http://localhost:5000/projects`,{
        headers:{
          username:res.data.login,
        }
      }).then((response)=>{
        setProjects(response.data)
      });
    }
    asyncFunc();
  }, []);

Upvotes: 1

Related Questions