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

Time:04-14

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.

CodePudding user response:

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: user }) => {
      setUser(user);

      return axios
        .get("http://localhost:5000/projects", {
          headers: { username: user.login },
        })
        .then(({ data: projects }) => {
          setProjects(projects);
        });
    })
    .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: user }) => {
      setUser(user);
    })
    .catch(console.error);
}, []);

useEffect(() => {
  axios
    .get("http://localhost:5000/projects", {
      headers: { username: user.login },
    })
    .then(({ data: projects }) => {
      setProjects(projects);
    })
    .catch(console.error);
}, [user]);

CodePudding user response:

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();
  }, []);
  • Related