Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
  }, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading