Birish
Birish

Reputation: 5832

Using Promise from Reactjs-promise returns an error

I'm trying to use reactjs-promise to get a value from an Ajax request, assign it to the component state, and use it in render() as follow:

import Promise from 'react-promise';
.....


componentWillMount(){
    var prom = new Promise( (resolve,reject) => {
        console.log("test1")    // Line A
        resolve(this.getUserID())
    });
    prom.then( value => {
        this.setState({userID: value})
    } )
},

getUserID(){
    console.log("test2")      //Line B
    var userID = null;
    // Call another method to run the ajax request...
    // ....
    return userID
},

render() {
    console.log(this.state.userID)
    return (....)
}

I'm getting this error:

 Uncaught TypeError: prom.then is not a function

Basically, I tried to follow the example here: https://www.npmjs.com/package/react-promise . Also, I expected Line A and Line B to show up in the console, but none of them happens. Can you help me to find the problem?

Upvotes: 1

Views: 2204

Answers (1)

Halfpint
Halfpint

Reputation: 4077

The problem here is that you are overriding the default reserved variable Promise with the react-promise library, instead you should change your import statement to:

import Async from 'react-promise';

Then you will be able to create a Promise object and pass that Promise as props to a node to be rendered by React (as described in the docs). For example:

import Async from 'react-promise'

let prom = new Promise(function (resolve, reject) {
setTimeout(function () {
     resolve('a value')
   }, 100)
})

const ExampleWithAsync = (props) => <Async promise={prom} then={(val) => <div>{val}</div>/>

The above code will set "a value" inside of the div upon resolving.

Upvotes: 1

Related Questions