I'm trying to have 3 fetch calls in my function.
First one:
This one gets me a random joke
fetch('https://v2.jokeapi.dev/joke/Programming')
.then((res) => res.json())
.then((actualResponse) => (joke = actualResponse.joke));
Second one:
I have to request a joke from a bot, think of it as a chatbot type of design. I ask for "hey, give me a joke" and then it gives me one. This one will get the "hey, give me a joke" send it to the back end and react will render it later on.
fetch('http://localhost:3002/jarvis/add', {
method: 'POST',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: messageInput.current.value,
author: 1,
}),
}).then((res) => res.json());
Third one:
This one is similar to the second one, its supposed to give the joke key the value of the joke variable, send it to the back end, and then react renders it later on.
fetch('http://localhost:3002/jarvis/add', {
method: 'POST',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json',
},
body: JSON.stringify({
joke: joke,
}),
}).then((res) => res.json());
My react can render things like this, so sending it to the backend and rendering works. I got a weather API working like this for example. I don't understand why this one isn't working out though, it feels like maybe its because it runs other functions before finishing? I don't know honestly and would appreciate someone more experienced feedback
I have realized I might need to use async/await, can someone point out why the following is not working? In my mind it does the first function, then the second one, then lastly the third one. It makes sense to me, clearly it's still not right though. This is the full code now:
async function getJoke() {
let joke = 'Im a robot';
await fetch('https://v2.jokeapi.dev/joke/Programming')
.then((res) => res.json())
.then((actualResponse) => (joke = actualResponse.joke));
await fetch('http://localhost:3002/jarvis/add', {
method: 'POST',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: messageInput.current.value,
author: 1,
}),
}).then((res) => res.json());
await fetch('http://localhost:3002/jarvis/add', {
method: 'POST',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json',
},
body: JSON.stringify({
joke: joke,
}),
}).then((res) => res.json());
}