mardi 27 octobre 2020

Reactjs: make a function to promise with axios in it

so I have this function in my context provider i want it to return a promise so that i can access to returned data from axios

    const sendRquest =(service,data,method,url)=>{
        let base = api.find(item => item.name ===service )
        let config = {
            method: method,
            url: `${base.url}/${url}`,
            headers: {
              'x-clientId': clientId,
              'Content-Type': 'application/json',
            },
            data: data
          };
          axios(config)
          .then(function (res) {
            return res
          })
          .catch(function (error) {
            return error
          });
    }

and the result I'm looking for is to write such code in every other component whenever I needed

sendRquest('usermanagement',data,'post','foo/bar').then(res=>console.log(res.data)).catch(err=>console.log(err))



Aucun commentaire:

Enregistrer un commentaire