Hi Friends 👋,
Welcome To Infinitbility! ❤️
To pass parameters to a promise function in react js, create a parameter function and use promise in a function like the below example.
var getNameById = function (id) {
return new Promise(function (resolve, reject) {
// ...
});
};
getNameById(3).then(function (res) {
console.log(res);
});
// output: "Stuff worked"
Today, I’m going to show you How do I pass parameters to a promise function in react js, as above mentioned, I’m going to use the above-mentioned syntax to create and use a promise function with a parameter.
Let’s start today’s tutorial how do you pass parameters to a promise function in react js?
React JS promise function with parameter example
Here we will create a parameter function and store it in a variable, in the function we will create a promise with a resolve & reject option where we will check if it is greater than 0 resolve promise or rejects.
import React, { useState, useEffect } from "react";
export default function App() {
const [str, setStr] = useState("");
useEffect(() => {
fetchFunction();
}, []);
const fetchFunction = async () => {
let res = await getNameById(3);
setStr(res);
};
const getNameById = (id) => {
return new Promise((resolve, reject) => {
if (id > 0) {
resolve("Stuff worked!");
} else {
reject(Error("It broke"));
}
});
};
return (
<div className="App">
<p>{str}</p>
</div>
);
}
In the above example, i have call promise function and store response in a state. printed state in a screen.
I hope it helps you, All the best 👍.