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.
1var getNameById = function (id) {2 return new Promise(function (resolve, reject) {3 // ...4 });5};67getNameById(3).then(function (res) {8 console.log(res);9});1011// 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.
1import React, { useState, useEffect } from "react";2export default function App() {3 const [str, setStr] = useState("");45 useEffect(() => {6 fetchFunction();7 }, []);89 const fetchFunction = async () => {10 let res = await getNameById(3);11 setStr(res);12 };1314 const getNameById = (id) => {15 return new Promise((resolve, reject) => {16 if (id > 0) {17 resolve("Stuff worked!");18 } else {19 reject(Error("It broke"));20 }21 });22 };2324 return (25 <div className="App">26 <p>{str}</p>27 </div>28 );29}
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 👍.
Follow me on Twitter
Join our email list and get notified about new content
No worries, I respect your privacy and I will never abuse your email.
Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.