localVarFormParams.getHeaders is not function when using openai.createImageEdit() - react-native

this is my function
const generatedDalleImage = async () => {
await openai.createImageEdit(
selectedImage,
selectedMaskImage,
"human face",
1,
"1024x1024"
).then((response) => {
console.log(response);
setGeneratedImage(response.data.data[0].url)
}).catch(err => {
console.log(err);
});
}
i am getting this error
localVarFormParams.getHeaders is not function when using openai.createImageEdit()
i am really stuck in this one so any help is appreciated

Related

Variables not registering in await function

What I'm trying to accomplish here is use req.body to pass the query arguments and when it hits the endpoint, the variables should be used in the create function of the Notion API. Unfortunately, the variables are registering as undefined. I figure that it's a scope issue, but I can't figure out how to structure this.
export default async function handler(req, res) {
const {
companyName,
email,
panelNames,
tags,
markers,
inquiry
} = req.body;
try {
await notion.pages
.create({
// use variables here
companyName: companyName //says undefined
}).then((result) => {
res.
})
} catch (e) {
console.log(e);
}
}
//Frontend code
const bodyQuery = {
companyName: "Example",
email: "example#gmail.com",
...
};
try {
await fetch("/api/v1/submit", headers)
.then((res) => {
return res.json();
})
.then((res) => {
setTests(res);
});
} catch (e) {
console.log("e:", e);
}
Because you did not pass bodyRequest to the request, so your backend can not receive data. Here's an example how to do it:
await fetch('/api/v1/submit', {
method: 'POST',
headers,
body: JSON.stringify(bodyRequest)
})
.then((res) => {
return res.json();
})
.then((res) => {
setTests(res);
});
And make sure your REST endpoint is POST. Hope it help!

React-native-fetch-blob GET request error

I am replacing axios to rn-fetch-blob in my react-native project. In the request I ping my server with credentials and I expect a response.
The old request with axios is as follows and works perfectly:
export const postWorkspace =
(newWorkspace: Workspace): AppThunk =>
async (dispatch) => {
console.log('addWorkspace Start');
dispatch(setIsLoading(true));
let configOption = {
headers: {
'Access-Control-Allow-Origin': '*',
'X-AUTH-USER': newWorkspace.credentials.email,
'X-AUTH-TOKEN': newWorkspace.credentials.password,
},
};
await axios
.get(`${newWorkspace.url}/api/ping`, configOption)
.then(async (resp) => {
console.log('addWorkspace resp', resp);
try {
await storeWorkspaceToStorage(newWorkspace);
} catch (e) {
console.error(e);
}
})
.catch((err) => {
console.log('addWorkspace err', JSON.stringify(err));
return Promise.reject(err);
})
.finally(() => dispatch(setIsLoading(false)));
};
This is how I transformed the code with rn-fetch-blob:
export const postWorkspace=
(newWorkspace: Workspace): AppThunk =>
async (dispatch) => {
console.log('addWorkspace Start');
dispatch(setIsLoading(true));
let configOption = {
'Access-Control-Allow-Origin': '*',
'X-AUTH-USER': newWorkspace.credentials.email,
'X-AUTH-TOKEN': newWorkspace.credentials.password,
};
await RNFetchBlob
.fetch('GET', '${newWorkspace.url}/api/ping', configOption)
.then( async(resp) => {
console.log('addWorkspace resp', resp);
try {
await storeWorkspaceToStorage(newWorkspace);
} catch (e) {
console.error(e);
}
})
.catch((err) => {
//console.log(err.info().status);
console.log('addWorkspace err', JSON.stringify(err));
return Promise.reject(err);
})
.finally(() => dispatch(setIsLoading(false)));
};
The new request with rn-fetch-blob returns this error:
response error "line":126349,"column":34,"sourceURL":"http://localhost:8081/index.bundle?platform=android&dev=true&minify=false"
When I opend the file "http://localhost:8081/index.bundle?platform=android&dev=true&minify=false" around line 1262349 the code looks like this, I can't understand what went wrong:
var req = RNFetchBlob[nativeMethodName];
req(options, taskId, method, url, headers || {}, body, function (err, rawType, data) {
subscription.remove();
subscriptionUpload.remove();
stateEvent.remove();
partEvent.remove();
delete promise['progress'];
delete promise['uploadProgress'];
delete promise['stateChange'];
delete promise['part'];
delete promise['cancel'];
promise.cancel = function () {};
//line 126349
if (err) reject(new Error(err, respInfo));else {
if (options.path || options.fileCache || options.addAndroidDownloads || options.key || options.auto && respInfo.respType === 'blob') {
if (options.session) session(options.session).add(data);
}
respInfo.rnfbEncode = rawType;
resolve(new FetchBlobResponse(taskId, respInfo, data));
}
});
});
I am doing this since rn-fetch-blob is basically one of the few libraries that allows react-native to ping a server with no SSL certification.
Thank you

Store the result of an async function into a variable

I am trying to store the result of an async function into a variable,but the output of my code didn't seems to be the expected one. What am I doing wrong ?
async function get_happy_songs() {
let urlOfS = 'http://10.0.2.2:5000/happy_songs'
try {
let response = await fetch(
urlOfS, {
method: 'GET'
}
);
let json = await response.json();
//console.log(json.melodies);
return json.melodies;
} catch (error) {
console.error(error);
}
}
//var happy_songs = [];
let happy_songs = get_happy_songs();
console.log(happy_songs)
Try like this.
async function get_happy_songs() {
let urlOfS = 'http://10.0.2.2:5000/happy_songs'
return fetch(urlOfS, {
method: 'GET'
}).then((response) => response.json())
.then((responseJson) => {
console.log('response object:', responseJson)
return responseJson;
})
.catch((error) => {
console.error(error);
});
}
let happy_songs = await get_happy_songs();
console.log(happy_songs)

Problem in reusable code to check internet availability in react native

I have made a function that checks for internet availability. whenever I call this function it gives me true every time whether the internet is ON or OFF. I want to have one function that contains code to check the internet and I can call it before fetching data from the internet . my code is below.
const [campusList, setCampusList]= React.useState([{label:'Select Campus', value:'select campus'}]);
const isConnected =()=>{
NetInfo.fetch().then(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
if(state.isConnected)
return true;
else
return false;
});
}
const loadCampuses = async()=>{
if(isConnected)
{
await fetch(url)
.then((respons)=>respons.json())
.then((jsonResponse)=>{
jsonResponse.map((data)=>
setCampusList(campusList=> [...campusList, {label:data.Text, value:data.Value}])
);
})
.catch((error)=>console.log(error))
//.finally(()=>setLoading(false))
}
}
fetch Returns a Promise that resolves to a NetInfoState object. you need to wait promise to resolve
try this
const isConnected = sendRequest => {
NetInfo.fetch().then(state => {
if (state.isConnected) {
sendRequest();
}
});
};
const loadCampuses = () => {
isConnected(async () => {
await fetch(url)
.then(respons => respons.json())
.then(jsonResponse => {
jsonResponse.map(data =>
setCampusList(campusList => [
...campusList,
{ label: data.Text, value: data.Value },
]),
);
})
.catch(error => console.log(error));
});
};
oh right, it's a promise, not just a straight return. you need to await for it. You don't need a separate function:
if(await NetInfo.fetch().isConnected)

await is only valid in async function - if else function

I check if there is such data in the firestore with (if (docSnapshot.exists)). I need to call await function when it goes inside else, but in this way I get an error "await is only valid in async function". How can I use the await function inside if else?
drawRoad = async (userLatitude,userLongitude,BranchLocationLatitude,BranchLocationLongitude,minPrice,shippingPrice) => {
try {
let userid = (this.props.UserStore.UserId).toString()
await firestore().collection('Tracking').doc(userid).onSnapshot(docSnapshot => {
if (docSnapshot.exists){
...
}
else {
...
let rsp=await fetch(url)
rsp=await rsp.json() }
}, err => {
console.log(`Encountered error: ${err}`);
});
} catch (error) {
console.log(error)
console.log("hata_componentDidMount HomeMap")
}
}
Try something like this:
else {
...
await fetch(url)
.then(res => res.json())
.then(res => do what you want with the response like setState, console.log it or whatever)
.catch(err => console.log(err))
}
Maybe try to tell the function to be async like this.
async function drawRoad(){
await fetch(url)
.then(res => res.json())
.then(res => {