Search code examples
reactjsapirequestaxiosstore

Best way to send data into multiple API using React Js


Now I have the following information (user data) to save. I have to send it to two APIs (URL). Like this.

http://api_url/users
http://api_url/user-card

Now i need send data to several API (URL) for save user and users' card information. I have the following data:

const [data] = useState({
    last_name: "",
    first_name: "",
    middle_name: "",
    card_number: "",
    card_given_date: "",
});

And like this post request using axios.

 api.post("/users", params)
        .then(res => {
            let response = res.data;
            console.log("Saved");
            setLoadingBtn(false);
            window.location = "/user/card/" + response.id;
        })
        .catch(e => {
            console.log(e.toString());
            setLoadingBtn(false);
        })

It works correctly for one API. I need to send the First Name, Last Name and Middle name to /users and user_id, card_number and card_given_date to the second api. What variants can I use to send POST requests to several APIs at the same time? Thanks!

UPDATED! Here's another logic. axios.all() and promises.all() are good solutions to get requests. But if we use them. Suppose a field in a table is empty or an error is filled. In this case the error is only transferred to one table and the other is saved. This leads to an error of logic. Like this:

 const addUserInfo = api.postItem("users", params);
        const addCardInfo = api.postItem("user-card", params2);
        Promise.all([addUserInfo, addCardInfo])
            .then(res => {
                let response = res.data;
                console.log("Saved");
                setLoadingBtn(false);
                window.location = "/user/card/" + response.id;
            })
            .catch(e => {
                console.log(e);
                console.log(e.toString());
                setLoadingBtn(false);
            });

This way leads to confusion of logic.


Solution

  • Based on your edit and comments you need to call the second api on the success of the first api like this:

    api.post("/users", params)
        .then(res => {
           let response = res.data;
           api.post("/users-card", params).then(res => {
               console.log("Saved");
               setLoadingBtn(false);
               window.location = "/user/card/" + response.id;
           });
       }).catch(e => {
            console.log(e.toString());
            setLoadingBtn(false);
        })